/*全局变量*/
var totalIndex = 0;
var currentSel;
/*--------*/
/*就绪函数*/
$(function(){
	var load_id = $('#load_id').val();
	if(load_id==null||load_id==""||load_id=="null"){
		
	}else{
		loadPaper(load_id);
	}
});
/*公共方法*/
//加载试卷更新填空题的填空
function updateLoadBlank(){
	var blankList = $('input[value="Blank"]').parents('.paper-subtopics-item');
	for(var i=0;i<blankList.length;i++){
		var _blanks = $(blankList[i]).find('.paper-subtopics-title input[type="text"]');
		var _answer = $(blankList[i]).find('.question-answer font span ');
		for(var j=0;j<_blanks.length;j++){
			$(_blanks[j]).val($(_answer[j]).text());
		}
	}
}
//更新大题分数
function updateScore(){
	var total_score = parseFloat(0);
	var topicsList = $('.paper-topics-item');
	for(var i=0;i<topicsList.length;i++){
		var topicsScore = parseFloat(0);
		var scoreList = $(topicsList[i]).find('.subtopics-score-input');
		for(var j=0;j<scoreList.length;j++){
			if($(scoreList).val()!=""&&$(scoreList).val()!=null)
				topicsScore += parseFloat($(scoreList).val());
		}
		total_score += topicsScore;
		$(topicsList[i]).find('.paper-topics-score i span').text(topicsScore);
	}
	$('#paper_score').next('div').find('span').text(total_score);
	$('.paper-total-score span').text(total_score);
}

/*生成唯一num*/
function newGuid()  
{  
    var guid = "";  
    for (var i = 1; i <= 32; i++){
      var n = Math.floor(Math.random()*16.0).toString(16);  
      guid +=   n;  
      if((i==8)||(i==12)||(i==16)||(i==20))  
        guid += "-";  
    }  
    return guid;      
}
/*填空题输入事件*/
function divInputChange(obj){
	var _subtopics = $(obj).parents('.paper-subtopics-item');
	var inputList = $(obj).find('input');
	var _answer = $(_subtopics).find('.question-answer font');
	var html = "";
	for(var i=0;i<inputList.length;i++){
		html += '<span class="blank-reference">'+$(inputList[i]).val()+'</span>';
	}
	$(_answer).html(html);
}
/*改变按钮可点击*/
function btnStatus(obj){
	$.each(obj,function(_key){
		$('#'+_key).attr('disabled',obj[_key]);
	});
}
/*判断题目是否已存在试卷*/
function isQuExist(id,quType){
	var subtopicsList = $('.paper-subtopics-item');
	for(var i=0;i<subtopicsList.length;i++){
		if($(subtopicsList[i]).find('.question-id').val()==id&&$.trim($(subtopicsList[i]).find('.question-type').val())==$.trim(quType))return true;
	}
	return false;
}
/*-----------*/
/*更新大题题标*/
function updateTopicsIndex(){
	var topicsList = $('.paper-topics-item');
	for(var i=0;i<topicsList.length;i++){
		$(topicsList[i]).find('.topics-index-value').val(i+1);
		$(topicsList[i]).find('.paper-topics-index span').text(getTopicsIndex(i+1));
		//同时更新小题里的radio和checkbox的name
		var subTopicsList = $(topicsList[i]).find('.paper-subtopics-item');
		for(var k=0;k<subTopicsList.length;k++){
			$(subTopicsList[k]).find('input[type="radio"]').attr('name','name_'+(i+1)+'_'+(k+1));
			$(subTopicsList[k]).find('input[type="checkbox"]').attr('name','name_'+(i+1)+'_'+(k+1));
		}
	}
}
function updateSubtopicsIndex(_topics){
	var subtopicsList = $(_topics).find('.paper-subtopics-item');
	for(var i=0;i<subtopicsList.length;i++){
		$(subtopicsList[i]).find('.subtopics-index-value').val(i+1);
		$(subtopicsList[i]).find('.paper-subtopics-index span').text(i+1);
		//同时更新小题里的radio和checkbox的name
		var _top_index = $(subtopicsList[i]).siblings('.topics-index-value').val();
		$(subtopicsList[i]).find('input[type="radio"]').attr('name','name_'+_top_index+'_'+(i+1));
		$(subtopicsList[i]).find('input[type="checkbox"]').attr('name','name_'+_top_index+'_'+(i+1));
	}
}
/*判断焦点题目类型*/
function isTopics(_focus){
	if(_focus.length==1){
		if($(_focus).attr('class').indexOf('paper-topics-item')>=0)return true;
		else return false;
	}else{
		return false;
	}
}
function isSubtopics(_focus){
	if(_focus.length==1){
		if($(_focus).attr('class').indexOf('paper-subtopics-item')>=0)return true;
		else return false;
	}else{
		return false;
	}
}
/*获取当前题标*/
function currentTopicsIndex(){
	var _focus = $('.topics-focus');
	if(_focus.length==1){
		if($(_focus).attr('class').indexOf('paper-subtopics-item')>=0){
			return parseInt($(_focus).siblings('.topics-index-value').val());
		}else if($(_focus).attr('class').indexOf('paper-topics-item')>=0){
			return parseInt($(_focus).find('.topics-index-value').val());
		}else{
			return null;
		}
	}else{
		return null
	}
}
function currentSubtopicsIndex(){
	var _focus = $('.topics-focus');
	if(_focus.length==1){
		if($(_focus).attr('class').indexOf('paper-subtopics-item')>=0){
			return parseInt($(_focus).find('.subtopics-index-value').val());
		}else if($(_focus).attr('class').indexOf('paper-topics-item')>=0){
			return -1;
		}else{
			return null;
		}
	}else{
		return null
	}
}
/*-------------------*/

function getCnIndex(num){
	return (0==num)?"零":(1==num)?"一":(2==num)?"二":(3==num)?"三":(4==num)?"四":(5==num)?"五":(6==num)?"六":(7==num)?"七":(8==num)?"八":(9==num)?"九":(10==num)?"十":(100==num)?"百":"";
}
function getTopicsIndex(num){
	//获取大题中文题标
	var index_1 = num%10;
	var index_10 = parseInt((num%100)/10);
	var index_100 = parseInt(num/100);
	return (num>0&&num<10)?getCnIndex(num):(num==10)?'十':(num>10&&num<20)?("十"+getCnIndex(index_1)):(num>=20&&num<100)?(getCnIndex(index_10)+"十"+getCnIndex(index_1)):(num>=100&&num<1000)?(getCnIndex(index_100)+"百"+getCnIndex(index_10)+"十"+getCnIndex(index_1)):"";
}
var optionsKey={
		"1":"A","2":"B","3":"C","4":"D","5":"E","6":"F","7":"G","8":"H","9":"I","10":"J","11":"K","12":"L","13":"M","14":"N","15":"O","16":"P","17":"Q","18":"R","19":"S","20":"T","21":"U","22":"V","23":"W","24":"X","25":"Y","26":"Z"
};
function getInputName(_subtopics,_sub_index){
	if($(_subtopics).attr('class').indexOf('paper-subtopics-item')>=0){
		var _name = "";
		
		var _topics_index = $(_subtopics).siblings('.topics-index-value').val();
		name = "name"+"_"+_topics_index+"_"+_sub_index;
		return name;
	}else{
		return "";
	}
}
function pasteHtmlAtCaret(html) {
	//在光标处插入html
    var sel, range;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            range = sel.getRangeAt(0);
            range.deleteContents();
            var el = document.createElement("div");
            el.innerHTML = html;
            var frag = document.createDocumentFragment(), node, lastNode;
            while ( (node = el.firstChild) ) {
                lastNode = frag.appendChild(node);
            };
            range.insertNode(frag);
            if (lastNode) {
                range = range.cloneRange();
                range.setStartAfter(lastNode);
                range.collapse(true);
                sel.removeAllRanges();
                sel.addRange(range);
            };
        };
    } else if (document.selection && document.selection.type != "Control") {
        // IE9以下
        document.selection.createRange().pasteHTML(html);
    };
};
function getBlankHtml(){
	//获取填空的html
	return '<input class="the-blank" required type="text" name="blank" onkeyup="changeText(this)" onchange="changeText(this)">';
}

function pasteImgAtCaret(sel,html) {
	//在光标处插入图片
    var range;
    if (sel.getRangeAt && sel.rangeCount) {
        range = sel.getRangeAt(0);
        range.deleteContents();
        var el = document.createElement("div");
        el.innerHTML = html;
        var frag = document.createDocumentFragment(), node, lastNode;
        while ( (node = el.firstChild) ) {
            lastNode = frag.appendChild(node);
        };
        range.insertNode(frag);
        if (lastNode) {
            range = range.cloneRange();
            range.setStartAfter(lastNode);
            range.collapse(true);
            sel.removeAllRanges();
            sel.addRange(range);
        };
    };
};
/*-------------------*/

/*新建构建大题编辑标签*/
function newTopics(_index){
	var html = '<div class="paper-topics-item">'+
					'<input type="hidden" class="topics-id">'+
					'<input type="hidden" class="topics-index-value" value="'+_index+'">'+
					'<div class="paper-topics-index"><span>'+getTopicsIndex(_index)+'</span>、</div>'+
					'<div class="paper-topics-title" contenteditable="true">'+
					'</div>'+
					'<font class="paper-topics-score" color="blue"><i>(分值：<span></span>)</i></font>'+
				'</div>';
	return html;
}
/*-------------------*/
/*新建构建小题题目标签*/
function newSingle(_top_index,_index){
	var html = '';
	html += '<div class="paper-subtopics-item">'+
				'<input type="hidden" class="subtopics-id">'+
				'<input type="hidden" class="question-type" value="Single">'+
				'<input type="hidden" class="subtopics-index-value" value='+_index+'>'+
				'<div class="paper-subtopics-index"><span>'+_index+'</span>、</div>'+
				'<div class="paper-subtopics-title" contenteditable="true">'+
				'</div>'+
				'<font color="blue"><i>(单选题)</i></font>'+
				'<div class="paper-subtopics-body">'+
					'<div class="subtopics-options-item">'+
						'<input type="hidden" class="question-options-id">'+
						'<input type="hidden" class="question-options-num">'+
						'<div class="question-options-index"><input onchange="answerSingle(this)" type="radio" name="name_'+_top_index+'_'+_index+'"><span>A</span>.</div>'+
						'<div class="question-options-content" contenteditable="true" ></div>'+
					'</div>'+
				'</div>'+
				'<div class="question-answer">参考答案：<font color="blue"></font></div>'+
				'<div class="paper-subtopics-score">'+
					'<span>分值：</span><input required onchange="_inputScore(this)" class="subtopics-score-input" onkeyup="value=value.replace(/[^\\d.]/g,\'\')" required type="text">'+
				'</div>'+
			'</div>';
	return html;
}
function newMultiple(_top_index,_index){
	var html = '';
	html += '<div class="paper-subtopics-item">'+
				'<input type="hidden" class="subtopics-id">'+
				'<input type="hidden" class="question-type" value="Multiple">'+
				'<input type="hidden" class="subtopics-index-value" value='+_index+'>'+
				'<div class="paper-subtopics-index"><span>'+_index+'</span>、</div>'+
				'<div class="paper-subtopics-title" contenteditable="true" >'+
				
				'</div>'+
				'<font color="blue"><i>(多选题)</i></font>'+
				'<div class="paper-subtopics-body">'+
					'<div class="subtopics-options-item">'+
						'<input type="hidden" class="question-options-id">'+
						'<input type="hidden" class="question-options-num">'+
						'<div class="question-options-index"><input onchange="answerMultiple(this)" type="checkbox" name="name_'+_top_index+'_'+_index+'"><span>A</span>.</div>'+
						'<div class="question-options-content" contenteditable="true"></div>'+
					'</div>'+
				'</div>'+
				'<div class="question-answer">参考答案：<font color="blue"></font></div>'+
				'<div class="paper-subtopics-score">'+
					'<span>分值：</span><input required onchange="_inputScore(this)" class="subtopics-score-input" onkeyup="value=value.replace(/[^\\d.]/g,\'\')" required type="text">'+
				'</div>'+
			'</div>';
	return html;
}
function newJudgment(_top_index,_index){
	var html = '';
	html += '<div class="paper-subtopics-item">'+
				'<input type="hidden" class="subtopics-id">'+
				'<input type="hidden" class="question-type" value="Judgment">'+
				'<input type="hidden" class="subtopics-index-value" value='+_index+'>'+
				'<div class="paper-subtopics-index"><span>'+_index+'</span>、</div>'+
				'<div class="paper-subtopics-title" contenteditable="true">'+
				
				'</div>'+
				'<font color="blue"><i>(判断题)</i></font>'+
				'<div class="paper-subtopics-body">'+
					'<div class="subtopics-options-item">'+
						'<label>'+
						'<input type="hidden" class="question-options-id">'+
						'<input type="hidden" class="question-options-num">'+
						'<input value=true onchange="answerJudgment(this)" type="radio" name="name_'+_top_index+'_'+_index+'"><span>正确</span>&nbsp;&nbsp;</label>'+
						'<label>'+
						'<input type="hidden" class="question-options-id">'+
						'<input type="hidden" class="question-options-num">'+
						'<input value=false onchange="answerJudgment(this)" type="radio" name="name_'+_top_index+'_'+_index+'"><span>错误</span></label>'+
					'</div>'+
				'</div>'+
				'<div class="question-answer">参考答案：<font color="blue"></font></div>'+
				'<div class="paper-subtopics-score">'+
					'<span>分值：</span><input required onchange="_inputScore(this)" class="subtopics-score-input" onkeyup="value=value.replace(/[^\\d.]/g,\'\')" required type="text">'+
				'</div>'+
			'</div>';
	return html;
}
function newBlank(_index){
	var html = '';
	html += '<div class="paper-subtopics-item">'+
				'<input type="hidden" class="subtopics-id">'+
				'<input type="hidden" class="question-type" value="Blank">'+
				'<input type="hidden" class="subtopics-index-value" value='+_index+'>'+
				'<div class="paper-subtopics-index"><span>'+_index+'</span>、</div>'+
				'<div onkeyup="divInputChange(this)" class="paper-subtopics-title" contenteditable="true">'+
				
				'</div>'+
				'<font color="blue"><i>(填空题)</i></font>'+
				'<div class="paper-subtopics-body">'+
				'</div>'+
				'<div class="question-answer">参考答案：<font color="blue"></font></div>'+
				'<div class="paper-subtopics-score">'+
					'<span>分值：</span><input required onchange="_inputScore(this)" class="subtopics-score-input" onkeyup="value=value.replace(/[^\\d.]/g,\'\')" required type="text">'+
				'</div>'+
			'</div>';
	return html;
}
function newExplanation(_index){
	var html = '';
	html += '<div class="paper-subtopics-item">'+
				'<input type="hidden" class="subtopics-id">'+
				'<input type="hidden" class="question-type" value="Explanation">'+
				'<input type="hidden" class="subtopics-index-value" value='+_index+'>'+
				'<div class="paper-subtopics-index"><span>'+_index+'</span>、</div>'+
				'<div class="paper-subtopics-title" contenteditable="true">'+
				
				'</div>'+
				'<font color="blue"><i>(解答题)</i></font>'+
				'<div class="paper-subtopics-body">'+
				'</div>'+
				'<div class="question-answer">参考答案：'+
					'<input type="hidden" class="question-options-id">'+
					'<div class="question-options-content" contenteditable="true"></div>'+
				'</div>'+
				'<div class="paper-subtopics-score">'+
					'<span>分值：</span><input required onchange="_inputScore(this)" class="subtopics-score-input" onkeyup="value=value.replace(/[^\\d.]/g,\'\')" required type="text">'+
				'</div>'+
			'</div>';
	return html;
}
function newSynthesized(_index){
	var html = '<div class="paper-topics-item">'+
		'<input type="hidden" class="topics-id">'+
		'<input type="hidden" class="topics-synthesized">'+
		'<input type="hidden" class="topics-index-value" value="'+_index+'">'+
		'<div class="paper-topics-index"><span>'+getTopicsIndex(_index)+'</span>、</div>'+
		'<div class="paper-topics-title" contenteditable="true">'+
		'</div>'+
		'<font class="paper-topics-score" color="blue"><i>(综合题，分值：<span></span>)</i></font>'+
	'</div>';
	return html;
}
/*-------------------*/
/*初始化*/


/*-----------*/
/*初始化1：取消按钮点击时获取焦点*/

var btns = $('.edit-paper-toolbar').find('.btn-group').find('.btn');
for(var i=0;i<btns.length;i++){
	$(btns[i]).bind('mousedown',function(event){
		event.preventDefault();
	});
}
/*var obj = {
		'btn_single':true,
		'btn_multiple':true,
		'btn_judgment':true,
		'btn_blank':true,
		'btn_explanation':true,
		'btn_synthesized':true,
		'btn_qubank':true,
		'btn_insert_option':true,
		'btn_insert_blank':true,
		'btn_insert_photo':true,
		'btn_insert_table':true,
		'btn_up':true,
		'btn_down':true,
		'btn_remove_option':true,
		'btn_remove_topic':true
		};
btnStatus(obj);*/
/*-------------------*/

/*初始化2：页面点击获取编辑题目焦点*/
$(document).bind('mousedown',function(e){
	var _this = e.target;
	var _this_topics = $(_this).parents('.paper-topics-item');
	var _this_subtopics = $(_this).parents('.paper-subtopics-item');
	var subtopicsEl = $(':focus').parents('.paper-subtopics-item');
	var topicsEl = $(':focus').parents('.paper-topics-item');
	if($.trim($(_this).attr('class'))==$.trim('paper-subtopics-item')||$.trim($(_this).attr('class'))==$.trim('paper-topics-item')){
		//点击了题目
		//移除原题目焦点
		$('.topics-focus').removeClass('topics-focus');
		$(_this).addClass('topics-focus');
	}else if(_this_subtopics.length==1){
		//移除原题目焦点
		$('.topics-focus').removeClass('topics-focus');
		
		$(_this_subtopics).addClass('topics-focus');
	}else if(_this_topics.length==1){
		//移除原题目焦点
		$('.topics-focus').removeClass('topics-focus');
		$(_this_topics).addClass('topics-focus');
	}else if(subtopicsEl.length==1){
		//移除原题目焦点
		$('.topics-focus').removeClass('topics-focus');
		
		$(subtopicsEl).addClass('topics-focus');
	}else if(topicsEl.length==1){
		//点击了大题
		//移除原题目焦点
		$('.topics-focus').removeClass('topics-focus');
		
		$(topicsEl).addClass('topics-focus');
	}else{
		
	}

	//更新按钮
/*	var _focus_class = $(':focus').attr('class');
	if($.trim(_focus_class)==$.trim('paper-topics-title')||$.trim(_focus_class)==$.trim('paper-subtopics-title')||$.trim(_focus_class)==$.trim('question-options-content')){
		var obj = {
				'btn_single':false,
				'btn_multiple':false,
				'btn_judgment':false,
				'btn_blank':false,
				'btn_explanation':false,
				'btn_synthesized':true,
				'btn_qubank':false,
				'btn_insert_option':true,
				'btn_insert_blank':true,
				'btn_insert_photo':true,
				'btn_insert_table':true,
				'btn_up':true,
				'btn_down':true,
				'btn_remove_option':true,
				'btn_remove_topic':true
			};
	}*/
});

/*-------------------*/
/*插入大题方法*/
function addTopics(){
	var _focus = $('.topics-focus');
	if(_focus.length==1){
		if($(_focus).attr('class').indexOf('paper-subtopics-item')>=0){
			//1当前焦点在小题上
			var _topics = $(_focus).parents('.paper-topics-item');
			var _index = parseInt($(_topics).find('.topics-index-value').val())+1;
			//修改焦点后大题题标
			var topicsList = $('.paper-topics-item');
			for(var i=_index-1;i<topicsList.length;i++){
				$(topicsList[i]).find('.topics-index-value').val(i+2);
				$(topicsList[i]).find('.paper-topics-index span').text(getTopicsIndex(i+2));
			}
			$(_topics).after(newTopics(_index));
		}else if($(_focus).attr('class').indexOf('paper-topics-item')>=0){
			//2当前焦点在大题上
			var _index = parseInt($(_focus).find('.topics-index-value').val())+1;
			
			//修改焦点后大题题标
			var topicsList = $('.paper-topics-item');
			for(var i=_index-1;i<topicsList.length;i++){
				$(topicsList[i]).find('.topics-index-value').val(i+2);
				$(topicsList[i]).find('.paper-topics-index span').text(getTopicsIndex(i+2));
			}
			
			$(_focus).after(newTopics(_index));
		}else{
			
		}
	}else{
		//3没有焦点
		var _index = $('.paper-topics-item').length+1;
		$('.edit-paper-body').append(newTopics(_index));
	}
}
/*-------------------*/

/*插入小题方法*/
function addSubTopics(quType){
	var _focus = $('.topics-focus');
	var _index;
	if(_focus.length==1){
		if($(_focus).attr('class').indexOf('paper-subtopics-item')>=0){
			//1当前焦点在小题上
			_index = parseInt($(_focus).find('.subtopics-index-value').val())+1;
			var _top_index = $(_focus).siblings('.topics-index-value').val();
			//修改焦点后小题题标
			var subtopicsList = $(_focus).nextAll('.paper-subtopics-item');
			var _top_index = $(_focus).siblings('.topics-index-value').val()
			for(var i=0;i<subtopicsList.length;i++){
				$(subtopicsList[i]).find('.subtopics-index-value').val(_index+i+1);
				$(subtopicsList[i]).find('.paper-subtopics-index span').text(_index+i+1);
				if($(subtopicsList[i]).find('.question-type').val()=="Single"||$(subtopicsList[i]).find('.question-type').val()=="Judgment"){
					$(subtopicsList[i]).find('input[type="radio"]').attr('name','name_'+_top_index+'_'+(_index+i+1));
				}else if($(subtopicsList[i]).find('.question-type').val()=="Multiple"){
					$(subtopicsList[i]).find('input[type="checkbox"]').attr('name','name_'+_top_index+'_'+(_index+i+1));
				}else{
					
				}
			}
			
			if($.trim(quType)==$.trim('Single')){
				//1单选题
				$(_focus).after(newSingle(_top_index,_index));
			}else if($.trim(quType)==$.trim('Multiple')){
				//2多选题

				$(_focus).after(newMultiple(_top_index,_index));
			}else if($.trim(quType)==$.trim('Judgment')){
				//3判断题

				$(_focus).after(newJudgment(_top_index,_index));
			}else if($.trim(quType)==$.trim('Blank')){
				//4填空题
				$(_focus).after(newBlank(_index));
			}else if($.trim(quType)==$.trim('Explanation')){
				//5解答题
				$(_focus).after(newExplanation(_index));
			}else if($.trim(quType)==$.trim('Synthesized')){
				//6综合题
				var topicsObj = $(_focus).parents('.paper-topics-item');
				//修改题标
				var topicsList = $(topicsObj).nextAll('.paper-topics-item');
				for(var i=0;i<topicsList.length;i++){
					$(topicsList[i]).find('.topics-index-value').val(parseInt(_top_index)+i+2);
					$(topicsList[i]).find('.paper-topics-index span').text(getTopicsIndex(parseInt(_top_index)+i+2));
				}
				//添加题目
				$(topicsObj).after(newSynthesized(parseInt(_top_index)+1));
			}else{
				
			}
		}else if($(_focus).attr('class').indexOf('paper-topics-item')>=0){
			//2当前焦点在大题上
			_index = parseInt($(_focus).find('.paper-subtopics-item').length)+1;
			var _top_index = $(_focus).find('.topics-index-value').val();
			if($.trim(quType)==$.trim('Single')){
				//1单选题
				$(_focus).append(newSingle(_top_index,_index));
			}else if($.trim(quType)==$.trim('Multiple')){
				//2多选题
				$(_focus).append(newMultiple(_top_index,_index));
			}else if($.trim(quType)==$.trim('Judgment')){
				//3判断题
				$(_focus).append(newJudgment(_top_index,_index));
			}else if($.trim(quType)==$.trim('Blank')){
				//4填空题
				$(_focus).append(newBlank(_index));
			}else if($.trim(quType)==$.trim('Explanation')){
				//5解答题
				$(_focus).append(newExplanation(_index));
			}else if($.trim(quType)==$.trim('Synthesized')){
				//6综合题
				//改变after的topics的index
				var topicsList = $(_focus).nextAll('.paper-topics-item');
				for(var i=0;i<topicsList.length;i++){
					$(topicsList[i]).find('.topics-index-value').val(parseInt(_top_index)+i+2);
					$(topicsList[i]).find('.paper-topics-index span').text(getTopicsIndex(parseInt(_top_index)+i+2));
				}
				//添加综合题
				$(_focus).after(newSynthesized(parseInt(_top_index)+1));
			}else{
				
			}
		}else{
			
		}
	}else{
		//3没有焦点
	}
}
/*-------------------*/
/*插入选项*/
function addSelection(){
	var _focus = $('.topics-focus');
	if($(_focus).attr('class').indexOf('paper-subtopics-item')>=0&&($(_focus).find('.question-type').val()=="Single"||$(_focus).find('.question-type').val()=="Multiple")){
		//此处可加入选项
		if($(':focus').parents('.subtopics-options-item').length>0&&$(':focus').parents('.paper-subtopics-item').length>0){
			var _subtopics = $(':focus').parents('.paper-subtopics-item');
			//1选择在选项下加入
			var _this = $(':focus');
			var _index = parseInt($(_this).parents('.subtopics-options-item').prevAll('.subtopics-options-item').length)+2;
			var theType = $($(_focus).find('.question-options-index input')).attr('type');
			var theName = $($(_focus).find('.question-options-index input')).attr('name');
			var html = '<div class="subtopics-options-item"><input type="hidden" class="question-options-id">';
			if($(_focus).find('.question-type').val()=="Single"){
				html += '<div class="question-options-index"><input onchange="answerSingle(this)" type="'+theType+'" name="'+theName+'"><span>'+optionsKey[_index]+'</span>.</div>';
			}else if($(_focus).find('.question-type').val()=="Multiple"){
				html += '<div class="question-options-index"><input onchange="answerMultiple(this)" type="'+theType+'" name="'+theName+'"><span>'+optionsKey[_index]+'</span>.</div>';
			}else{
				
			}
			
			html += '<div class="question-options-content" contenteditable="true" onfocus="if(this.innerText==\'输入内容\')this.innerText=\'\'" onblur="if(this.innerText==\'\')this.innerText=\'输入内容\'">输入内容</div>'+
					'</div>';
			$(_this).parents('.subtopics-options-item').after(html);
			//更新选项题标//更新答案
			if($(_focus).find('.question-type').val()=="Single"){
				updateSingleIndex(_subtopics);
				updateSingleReference(_subtopics);
			}else if($(_focus).find('.question-type').val()=="Multiple"){
				updateMultipleIndex(_subtopics);
				updateMultipleReference(_subtopics);
			}else{
				
			}
			
		}else{
			//2选择在最后加入
			alert(0000)
			var _index = parseInt($(_focus).find('.subtopics-options-item').length)+1;
			var theType = $($(_focus).find('.question-options-index input')[0]).attr('type');
			var theName = $($(_focus).find('.question-options-index input')[0]).attr('name');
			var html = '<div class="subtopics-options-item"><input type="hidden" class="question-options-id">';
			if($(_focus).find('.question-type').val()=="Single"){
				html += '<div class="question-options-index"><input onchange="answerSingle(this)" type="'+theType+'" name="'+theName+'"><span>'+optionsKey[_index]+'</span>.</div>';
			}else if($(_focus).find('.question-type').val()=="Multiple"){
				html += '<div class="question-options-index"><input onchange="answerMultiple(this)" type="'+theType+'" name="'+theName+'"><span>'+optionsKey[_index]+'</span>.</div>';
			}else{
				
			}
							
			html += '<div class="question-options-content" contenteditable="true" onfocus="if(this.innerText==\'输入内容\')this.innerText=\'\'" onblur="if(this.innerText==\'\')this.innerText=\'输入内容\'">输入内容</div>'+
						'</div>';
			$(_focus).find('.paper-subtopics-body').append(html);
			//更新选项题标//更新答案
			if($(_focus).find('.question-type').val()=="Single"){
				updateSingleIndex(_subtopics);
				updateSingleReference(_subtopics);
			}else if($(_focus).find('.question-type').val()=="Multiple"){
				updateMultipleIndex(_subtopics);
				updateMultipleReference(_subtopics);
			}else{
				
			}
		}
	}else{
		alert("不能在此处加入选项!");
	}
}
/*-------------------*/
/*题目上移*/
function topicsUp(){
	var _focus = $('.topics-focus');
	
	if(_focus.length==1){
		if($(_focus).attr('class').indexOf('paper-subtopics-item')>=0){
			//焦点在小题上
			var _up = $(_focus).prev('.paper-subtopics-item');
			if(_up.length<=0){
				//题目已经是第一题
				
			}else{
				//上移操作
				//1改变题标
				var _index_temp = $(_up).find('.subtopics-index-value').val();
				var _index_contr = $(_focus).find('.subtopics-index-value').val();
				
				$(_up).find('.subtopics-index-value').val(_index_contr);
				$(_up).find('.paper-subtopics-index span').text(_index_contr);
				$(_focus).find('.subtopics-index-value').val(_index_temp);
				$(_focus).find('.paper-subtopics-index span').text(_index_temp);
				//同时修改选项radio的name
				var _up_quTypeObj = $(_up).find('.question-type');
				if($.trim($(_up_quTypeObj).val())==$.trim('Single')||$.trim($(_up_quTypeObj).val())==$.trim('Multiple')){
					var _indexList = $(_up).find('.question-options-index input');
					for(var i=0;i<_indexList.length;i++){
						$(_indexList[i]).attr('name',getInputName(_up,_index_contr));
					}
				}else if($.trim($(_up_quTypeObj).val())==$.trim('Judgment')){
					var _indexList = $(_up).find('.subtopics-options-item label input');
					for(var i=0;i<_indexList.length;i++){
						$(_indexList[i]).attr('name',getInputName(_up,_index_contr));
					}
				}else{
					
				}
				
				var _contr_quTypeObj = $(_focus).find('.question-type');
				if($.trim($(_contr_quTypeObj).val())==$.trim('Single')||$.trim($(_contr_quTypeObj).val())==$.trim('Multiple')){
					var _indexList = $(_focus).find('.question-options-index input');
					for(var i=0;i<_indexList.length;i++){
						$(_indexList[i]).attr('name',getInputName(_focus,_index_temp));
					}
				}else if($.trim($(_contr_quTypeObj).val())==$.trim('Judgment')){
					var _indexList = $(_focus).find('.subtopics-options-item label input');
					for(var i=0;i<_indexList.length;i++){
						$(_indexList[i]).attr('name',getInputName(_focus,_index_temp));
					}
				}else{
					
				}
				//2交换元素
				var new_focus = $('.topics-focus');
				var new_up = $(new_focus).prev('.paper-subtopics-item');
				new_focus.insertBefore(new_up);
			}
		}else if($(_focus).attr('class').indexOf('paper-topics-item')>=0){
			//焦点在大题上
			var _up = $(_focus).prev('.paper-topics-item');
			if(_up.length<=0){
				//已经是第一题
			}else{
				//1改变题标
				var _up_index = $(_up).find('.topics-index-value').val();
				var _contr_index = $(_focus).find('.topics-index-value').val();
				
				$(_up).find('.topics-index-value').val(_contr_index);
				$(_focus).find('.topics-index-value').val(_up_index);
				
				$(_up).find('.paper-topics-index span').text(getTopicsIndex(_contr_index));
				$(_focus).find('.paper-topics-index span').text(getTopicsIndex(_up_index));
				//2交换元素
				_focus.insertBefore(_up);
			}
			
		}else{
			
		}
	}else{
		alert("没有题目被选中!");
	}
}
/*-------------------*/
/*题目下移*/
function topicsDown(){
	var _focus = $('.topics-focus');
	
	if(_focus.length==1){
		if($(_focus).attr('class').indexOf('paper-subtopics-item')>=0){
			//选择小题
			var _down = $(_focus).next('.paper-subtopics-item');
			if(_down.length<=0){
				//题目已经是最后一题
				
			}else{
				//下移操作
				//1改变题标
				var _index_temp = $(_down).find('.subtopics-index-value').val();
				var _index_contr = $(_focus).find('.subtopics-index-value').val();
				
				$(_down).find('.subtopics-index-value').val(_index_contr);
				$(_down).find('.paper-subtopics-index span').text(_index_contr);
				$(_focus).find('.subtopics-index-value').val(_index_temp);
				$(_focus).find('.paper-subtopics-index span').text(_index_temp);
				//同时修改选项radio的name
				var _down_quTypeObj = $(_down).find('.question-type');
				if($.trim($(_down_quTypeObj).val())==$.trim('Single')||$.trim($(_down_quTypeObj).val())==$.trim('Multiple')){
					var _indexList = $(_down).find('.question-options-index input');
					for(var i=0;i<_indexList.length;i++){
						$(_indexList[i]).attr('name',getInputName(_down,_index_contr));
					}
				}else if($.trim($(_down_quTypeObj).val())==$.trim('Judgment')){
					var _indexList = $(_down).find('.subtopics-options-item label input');
					for(var i=0;i<_indexList.length;i++){
						$(_indexList[i]).attr('name',getInputName(_down,_index_contr));
					}
				}else{
					
				}
				
				var _contr_quTypeObj = $(_focus).find('.question-type');
				if($.trim($(_contr_quTypeObj).val())==$.trim('Single')||$.trim($(_contr_quTypeObj).val())==$.trim('Multiple')){
					var _indexList = $(_focus).find('.question-options-index input');
					for(var i=0;i<_indexList.length;i++){
						$(_indexList[i]).attr('name',getInputName(_focus,_index_temp));
					}
				}else if($.trim($(_contr_quTypeObj).val())==$.trim('Judgment')){
					var _indexList = $(_focus).find('.subtopics-options-item label input');
					for(var i=0;i<_indexList.length;i++){
						$(_indexList[i]).attr('name',getInputName(_focus,_index_temp));
					}
				}else{
					
				}
				//2交换元素
				var new_focus = $('.topics-focus');
				var new_down = $(new_focus).next('.paper-subtopics-item');
				new_down.insertBefore(new_focus);
			}
		}else if($(_focus).attr('class').indexOf('paper-topics-item')>=0){
			//选择大题
			var _down = $(_focus).next('.paper-topics-item');
			if(_down.length<=0){
				//已经是最后一题
			}else{
				//1改变题标
				var _down_index = $(_down).find('.topics-index-value').val();
				var _contr_index = $(_focus).find('.topics-index-value').val();
				
				$(_down).find('.topics-index-value').val(_contr_index);
				$(_focus).find('.topics-index-value').val(_down_index);
				
				$(_down).find('.paper-topics-index span').text(getTopicsIndex(_contr_index));
				$(_focus).find('.paper-topics-index span').text(getTopicsIndex(_down_index));
				//2交换元素
				_down.insertBefore(_focus);
			}
		}else{
			
		}
	}else{
		//没有题目选中
		alert("没有题目被选中!");
	}
}
/*-------------------*/
/*删除选项*/
function removeOptions(){
	var _focus = $(':focus');
	if($(_focus).attr('class')!=null&&$(_focus).attr('class').indexOf('question-options-content')>=0){
		if($(_focus).parents('.subtopics-options-item').siblings('.subtopics-options-item').length<=0){
			//只有一项
			if(confirm("确认要删除选项吗?")){
				$(_focus).text("");
				$(_focus).siblings('.question-options-index').find('input').removeAttr('checked');
				var _subtopics = $(_focus).parents('.paper-subtopics-item');
				if($(_subtopics).find('.question-type').val()=="Single"){
					updateSingleReference(_subtopics);
				}else if($(_subtopics).find('.question-type').val()=="Multiple"){
					updateMultipleReference(_subtopics);
				}else{
					
				}
			}
		}else if(confirm("确认要删除选项吗?")){
			var _itemList = $(_focus).parents('.subtopics-options-item').nextAll('.subtopics-options-item');
			var _prevLength = parseInt($(_focus).parents('.subtopics-options-item').prevAll('.subtopics-options-item').length);
			for(var i=0;i<_itemList.length;i++){
				$(_itemList[i]).find('.question-options-index span').text(optionsKey[i+1+_prevLength]);
			}
			var _subtopics = $(_focus).parents('.paper-subtopics-item');
			$(_focus).parents('.subtopics-options-item').remove();
			//更新答案选项
			if($(_subtopics).find('.question-type').val()=="Single"){
				updateSingleReference(_subtopics);
			}else if($(_subtopics).find('.question-type').val()=="Multiple"){
				updateMultipleReference(_subtopics);
			}else{
				
			}
		}else{
			
		}
	}else{
		alert("没有选项被选中！");
	}
}
/*-------------------*/
/*删除题目*/
function removeTopics(){
	var _focus = $('.topics-focus');
	if(_focus.length<=0)return;
	if($(_focus).attr('class').indexOf('paper-subtopics-item')>=0){
		//焦点在小题
		if(confirm("确认要删除该小题吗?")){
			var _nextList = $(_focus).nextAll('.paper-subtopics-item');
			for(var i=0;i<_nextList.length;i++){
				var _index = parseInt($(_nextList[i]).find('.subtopics-index-value').val())-1;
				$(_nextList[i]).find('.subtopics-index-value').val(_index);
				$(_nextList[i]).find('.paper-subtopics-index span').text(_index);
			}
			$(_focus).remove();
		}
	}else if($(_focus).attr('class').indexOf('paper-topics-item')>=0){
		//焦点在大题
		if(confirm("确认移除整道大题吗?")){
			var _nextList = $(_focus).nextAll('.paper-topics-item');
			for(var i=0;i<_nextList.length;i++){
				var _index = parseInt($(_nextList[i]).find('.topics-index-value').val())-1;
				$(_nextList[i]).find('.topics-index-value').val(_index);
				$(_nextList[i]).find('.paper-topics-index span').text(getTopicsIndex(_index));
			}
			$(_focus).remove();
		}
	}else{
		
	}
}
/*-------------------*/
/*插入填空*/
function insertBlank(){
	var _focus = $(':focus');
	if(_focus.length==1){
		if($.trim($(_focus).siblings('.question-type').val())==$.trim('Blank')){
			pasteHtmlAtCaret(getBlankHtml());
		}else{
			alert("此处不可插入填空!");
		}
	}else{
		
	}
}
/*-------------------*/
/*打开插入图片窗口*/
function openInsertImgWin(){
	var _focus = $(':focus');
	if(_focus.length==1){
		currentSel = window.getSelection(); 
		var _class = $(_focus).attr('class');
		if($.trim(_class)==$.trim('paper-subtopics-title')||$.trim(_class)==$.trim('paper-topics-title')||$.trim(_class)==$.trim('question-options-content')){
			$('#insertImgModal').modal('show');
			//初始化图片上传#imgUpload
			
		}else{
			alert("此处不可插入图片!");
		}
	}else{
		
	}
}
/*-------------------*/
/*确定插入图片*/
function insertImg(){
	var imgSrc = $('#imgPrev').attr('src');
	if($.trim(imgSrc)==$.trim('')){
		alert("请选择图片!");
		return;
	}
	var imgWidth = $('#imgPrev').attr('width');
	var node = document.createElement("img");
	$(node).attr('src',imgSrc);
	$(node).attr('width',imgWidth);
	currentSel.getRangeAt(0).insertNode(node);
	
	//初始化模态框
	$('#imgPrev').attr('src','');
	$('#imgUpload').val('');
	$('#imgSize').val(50);
	$('#insertImgModal').modal('hide');
}
/*-------------------*/
/*图片改变*/
function imgValueChange(){
	if($('#imgUpload').val()!=null&&$('#imgUpload').val()!=""){
		$('#imgUploadForm').ajaxSubmit({
				dataType: "json",
			    success: function(data){
					$("#imgPrev").attr('src',data.data);
			    }
			});
	}else{
		
	}
}
/*-------------------*/
/*图片尺寸改变*/
function changeImgSize(){
	console.log($('#imgSize').val());
	var _size = 800*($('#imgSize').val()/100);
	$('#imgPrev').attr('width',_size);
}
/*-------------------*/
/*选择判断题答案*/
function answerJudgment(obj){
	var bodyObj = $(obj).parents('.paper-subtopics-body');
	var referenceObj = $(bodyObj).siblings('.question-answer');
	if($(obj).val()=='true'){
		$(referenceObj).find('font').html('<span class="fa fa-check"></span>');
	}else if($(obj).val()=='false'){
		$(referenceObj).find('font').html('<span class="fa fa-close"></span>');
	}
}
/*-------------------*/
/*选择单选题答案*/
function answerSingle(obj){
	var bodyObj = $(obj).parents('.paper-subtopics-body');
	var referenceObj = $(bodyObj).siblings('.question-answer');
	var answer = $(obj).siblings('span').text();
	$(referenceObj).find('font').text(answer);
	
}
/*-------------------*/
/*选择多选题答案*/
function answerMultiple(obj){
	var bodyObj = $(obj).parents('.paper-subtopics-body');
	var referenceObj = $(bodyObj).siblings('.question-answer');
	var selList = $(bodyObj).find('input[type="checkbox"]:checked');
	
	var _value = "";
	for(var i=0;i<selList.length;i++){
		_value += $(selList[i]).siblings('span').text();
	}
	$(referenceObj).find('font').text(_value);
	
}
/*-------------------*/
/*更新单选题选项题标*/
function updateSingleIndex(singleObj){
	var optionList = $(singleObj).find('.subtopics-options-item');
	for(var i=0;i<optionList.length;i++){
		$(optionList[i]).find('span').text(optionsKey[i+1]);
	}
}
/*-------------------*/
/*更新单选题所选答案*/
function updateSingleReference(singleObj){
	var selOption = $(singleObj).find('input[type="radio"]:checked');
	if(selOption!=null){
		$(singleObj).find('.question-answer font').text($(selOption).siblings('span').text());
	}else{
		//未选答案
	}
}
/*-------------------*/
/*更新多选题选项题标*/
function updateMultipleIndex(multipleObj){
	var optionList = $(multipleObj).find('.subtopics-options-item');
	for(var i=0;i<optionList.length;i++){
		$(optionList[i]).find('span').text(optionsKey[i+1]);
	}
}
/*-------------------*/
/*更新多选题所选答案*/
function updateMultipleReference(multipleObj){
	var selOptions = $(multipleObj).find('input[type="checkbox"]:checked');
	var _answer = "";
	for(var i=0;i<selOptions.length;i++){
		_answer += $(selOptions[i]).siblings('span').text();
	}
	$(multipleObj).find('.question-answer font').text(_answer);
}
/*-------------------*/
/*输入小题分数，计算大题分数、试卷分数*/
function _inputScore(obj){
	updateScore();
}
/*-------------------*/
/*更新总分*/
function updateTopicsScore(){
	var topicsList = $('.paper-topics-item');
	var total_score = parseFloat(0);
	for(var i=0;i<topicsList.length;i++){
		var subtopicsList = $(topicsList[i]).find('.paper-subtopics-item');
		var topics_score = parseFloat(0);
		for(var j=0;j<subtopicsList.length;j++){
			var _value = $(subtopicsList[j]).find('.subtopics-score-input').val();
			if(_value!=""&&_value!=null){
				topics_score += parseFloat(_value);
			}
		}
		total_score += topics_score;
		
		$(topicsList[i]).find('.paper-topics-score i span').text(topics_score);
	}
	$('.paper-topics-score span').text(total_score);
	$('#paper_score').next('div').find('span').text(total_score);
}
/*-------------------*/
/*判断div输入是否为空*/
function isInputEmpty(divObj){
	var num = (($(divObj).html().split(' ')).length-1)+(($(divObj).html().split('&nbsp;')).length-1)*6;
    if($(divObj).html()==""||$(divObj).html().length==num)return true;
    else return false;
}
/*-------------------*/
/*打开题库模态框*/
function openQuModel(){
	if($('.topics-focus').length<=0){
		alert("没有选择题目!");
		return;
	}
	$('#quListModel').modal('show');
	showSingleTable();
	showMultipleTable();
	showJudgmentTable();
	showBlankTable();
	showExplanationTable();
	showSynthesizedTable();
}
/*-------------------*/
/*加载题库列表*/
function showSingleTable(){
	//单选题加载表格
	$('#singleTable').bootstrapTable({
		url:'single/findRealPage', // 服务器数据的加载地址
		method: 'get',  
	    dataType: "json",  
	    striped: true,// 设置为 true 会有隔行变色效果
	    undefinedText: "空",// 当数据为 undefined 时显示的字符
	    pagination: true, // 分页
	    toolbar: '#toolbar',
	   // paginationLoop:true,//设置为 true 启用分页条无限循环的功能。
	    // showToggle: "true",//是否显示 切换试图（table/card）按钮
	    // showColumns: "true",//是否显示 内容列下拉框
	    showRefresh: true,// 是否显示刷新按钮
	    pageNumber: 1,// 如果设置了分页，首页页码
	    // showPaginationSwitch:true,//是否显示 数据条数选择框
	    pageSize: 6,// 如果设置了分页，页面数据条数
	    // pageList: [5, 10, 20, 40], //如果设置了分页，设置可供选择的页面数据条数。设置为All 则显示所有记录。
	    paginationPreText: '‹',// 指定分页条中上一页按钮的图标或文字,这里是<
	    paginationNextText: '›',// 指定分页条中下一页按钮的图标或文字,这里是>
	    // singleSelect: false,//设置True 将禁止多选
	    // search: true, //显示搜索框
	    data_local: "zh-US",
	    sidePagination: "server",
	    queryParams: function (params) {
	        return {
				page:(params.offset)/(params.limit)+1,
	            limit: params.limit,
	            sort:params.sort,
	            dir:params.order
	        };
	    },
	    idField: "id",// 指定主键列
	    columns: [
	    	{
	    		field:'id',
	    		title:'ID'
	    	},{
	    		title:'题目',
	    		formatter: function(value,row,index){
	    			var html = '<div class="quest-title-display">'+row.title+'</div>';
					var content = '';
					var length = Object.keys(row.options).length;
					var answerKey;
					for(var i=0;i<length;i++){
						if(i%2==0){
							content += '<ul class="row list-style-none">';
							content += '<li class="col-sm-6 quest-display">';
							if(row.answer.id==row.options[optionsKey[i+1]].id)
								answerKey = optionsKey[i+1];
							content += '<p>'+optionsKey[i+1]+'.</p>'+row.options[optionsKey[i+1]].content;
							content += '</li>';
						}else{
							content += '<li class="col-sm-6 quest-display">';
							if(row.answer.id==row.options[optionsKey[i+1]].id)
								answerKey = optionsKey[i+1];
							content += '<p>'+optionsKey[i+1]+'.</p>'+row.options[optionsKey[i+1]].content;
							content += '</li>';
							if(i!=0)
								content += '</ul>';
						}
					}
					content += '</ul>';
					content += '<font color="red">正确答案：'+answerKey+'</font>';
					html += content;
					
	    			return html;
	    		}
	    	},{
		        title: '操作',
		        formatter : function(value,row,index){
		        	var r = '<a class="fa fa-check-square-o btn btn-info" title="选择插入" onclick="loadSingle('+row.id+')">选择</a>';
		        	return r;
	        }
	    }]
	      
	});
}
function showMultipleTable(){
	// 多选题加载表格
	$('#multipleTable').bootstrapTable({
		url:'multiple/findRealPage', // 服务器数据的加载地址
		method: 'get',  
	    dataType: "json",  
	    striped: true,// 设置为 true 会有隔行变色效果
	    undefinedText: "空",// 当数据为 undefined 时显示的字符
	    pagination: true, // 分页
	    toolbar: '#toolbar',
	   // paginationLoop:true,//设置为 true 启用分页条无限循环的功能。
	    // showToggle: "true",//是否显示 切换试图（table/card）按钮
	    // showColumns: "true",//是否显示 内容列下拉框
	    showRefresh: true,// 是否显示刷新按钮
	    pageNumber: 1,// 如果设置了分页，首页页码
	    // showPaginationSwitch:true,//是否显示 数据条数选择框
	    pageSize: 6,// 如果设置了分页，页面数据条数
	    // pageList: [5, 10, 20, 40], //如果设置了分页，设置可供选择的页面数据条数。设置为All 则显示所有记录。
	    paginationPreText: '‹',// 指定分页条中上一页按钮的图标或文字,这里是<
	    paginationNextText: '›',// 指定分页条中下一页按钮的图标或文字,这里是>
	    // singleSelect: false,//设置True 将禁止多选
	    // search: true, //显示搜索框
	    data_local: "zh-US",// 表格汉化
	    sidePagination: "server", // 服务端处理分页
	    queryParams: function (params) {
	        return {
				page:(params.offset)/(params.limit)+1,
	            limit: params.limit,
	            sort:params.sort,
	            dir:params.order
	        };
	    },
	    idField: "id",// 指定主键列
	    columns: [
	    	{
	    		field:'id',
	    		title:'ID'
	    	},
	    	{
	    		title:'题目',
	    		formatter: function(value,row,index){
	    			var html = '<div class="quest-title-display">'+row.title+'</div>';
	    			var content = '';
					var length = Object.keys(row.options).length;
					var answerKey = new Array();
					
					for(var i=0;i<length;i++){
						if(i%2==0){
							for(var j=0;j<row.answers.length;j++){
								if(row.answers[j].id==row.options[optionsKey[i+1]].id){
									answerKey.push(optionsKey[i+1]);
								}
							}
							
							content += '<ul class="row list-style-none">';
							content += '<li class="col-sm-6 quest-display">';
							content += '<p>'+optionsKey[i+1]+'.</p>'+row.options[optionsKey[i+1]].content;
							content += '</li>';
							if(i==(length-1))
								content += '</ul>';
						}else{
							for(var j=0;j<row.answers.length;j++){
								if(row.answers[j].id==row.options[optionsKey[i+1]].id){
									answerKey.push(optionsKey[i+1]);
								}
							}
							
							content += '<li class="col-sm-6 quest-display">';
							content += '<p>'+optionsKey[i+1]+'.</p>'+row.options[optionsKey[i+1]].content;
							content += '</li>';
							if(i!=0)
								content += '</ul>';
						}
					}
					
					content += '<font color="red">正确答案：';
					for(var k=0;k<answerKey.length;k++){
						content += answerKey[k];
					}
					content += '</font>';
					html += content;
	    			return html;
	    		}
	    	},{
	        title: '操作',
	        formatter : function(value,row,index){
	        	var r = '<a class="fa fa-check-square-o btn btn-info" title="选择插入" onclick="loadMultiple('+row.id+')">选择</a>';
	        	return r;
        	}
	        }]
	      
	});
}
function showJudgmentTable(){
	// 判断题加载表格
	$('#judgmentTable').bootstrapTable({
		url:'judgment/findRealPage', // 服务器数据的加载地址
		method: 'get',  
	    dataType: "json",  
	    striped: true,// 设置为 true 会有隔行变色效果
	    undefinedText: "空",// 当数据为 undefined 时显示的字符
	    pagination: true, // 分页
	    toolbar: '#toolbar',
	   // paginationLoop:true,//设置为 true 启用分页条无限循环的功能。
	    // showToggle: "true",//是否显示 切换试图（table/card）按钮
	    // showColumns: "true",//是否显示 内容列下拉框
	    showRefresh: true,// 是否显示刷新按钮
	    pageNumber: 1,// 如果设置了分页，首页页码
	    // showPaginationSwitch:true,//是否显示 数据条数选择框
	    pageSize: 6,// 如果设置了分页，页面数据条数
	    // pageList: [5, 10, 20, 40], //如果设置了分页，设置可供选择的页面数据条数。设置为All 则显示所有记录。
	    paginationPreText: '‹',// 指定分页条中上一页按钮的图标或文字,这里是<
	    paginationNextText: '›',// 指定分页条中下一页按钮的图标或文字,这里是>
	    // singleSelect: false,//设置True 将禁止多选
	    // search: true, //显示搜索框
	    data_local: "zh-US",// 表格汉化
	    sidePagination: "server",
	    queryParams: function (params) {
	        return {
				page:(params.offset)/(params.limit)+1,
	            limit: params.limit,
	            sort:params.sort,
	            dir:params.order
	        };
	    },
	    idField: "id",// 指定主键列
	    columns: [
	    	{
	    		field:'id',
	    		title:'ID'
	    	},
			{
		        title: '题目',
		        formatter : function(value,row,index){
		        	var html = '<div class="quest-title-display">'+row.title+'</div>';
					if(row.answer.content=='true'){
						html += '<font color=\"red\">答案:√</font>';
					}else{
						html += '<font color=\"red\">答案:×</font>';
					}
					
					return html;
		        }
	    	},{
		        title: '操作',
		        formatter : function(value,row,index){
		        	var r = '<a class="fa fa-check-square-o btn btn-info" title="选择插入" onclick="loadJudgment('+row.id+')">选择</a>';
		        	return r;
				}
		        }
	    	]
	      
	});
}
function showBlankTable(){
	// 填空题加载表格
	$('#blankTable').bootstrapTable({
		url:'blank/findPage', // 服务器数据的加载地址
		method: 'get',  
	    dataType: "json",  
	    striped: true,// 设置为 true 会有隔行变色效果
	    undefinedText: "空",// 当数据为 undefined 时显示的字符
	    pagination: true, // 分页
	    toolbar: '#toolbar',
	   // paginationLoop:true,//设置为 true 启用分页条无限循环的功能。
	    // showToggle: "true",//是否显示 切换试图（table/card）按钮
	    // showColumns: "true",//是否显示 内容列下拉框
	    showRefresh: true,// 是否显示刷新按钮
	    pageNumber: 1,// 如果设置了分页，首页页码
	    // showPaginationSwitch:true,//是否显示 数据条数选择框
	    pageSize: 6,// 如果设置了分页，页面数据条数
	    // pageList: [5, 10, 20, 40], //如果设置了分页，设置可供选择的页面数据条数。设置为All 则显示所有记录。
	    paginationPreText: '‹',// 指定分页条中上一页按钮的图标或文字,这里是<
	    paginationNextText: '›',// 指定分页条中下一页按钮的图标或文字,这里是>
	    // singleSelect: false,//设置True 将禁止多选
	    // search: true, //显示搜索框
	    data_local: "zh-US",// 表格汉化
	    sidePagination: "server",
	    queryParams: function (params) {
	        return {
				page:(params.offset)/(params.limit)+1,
	            limit: params.limit,
	            sort:params.sort,
	            dir:params.order
	        };
	    },
	    idField: "id",// 指定主键列
	    columns: [
	    	{
	    		field:'id',
	    		title:'ID'
	    	},
			{
		        title: '题目',
		        formatter : function(value,row,index){
		        	var html = '<div class="quest-title-display">'+row.content+'</div>';
		        	html += '<font color=\"red\">参考答案：';
		        	var length = Object.keys(row.blanks).length;
					for(var i=0;i<length;i++){
						html += row.blanks[i+1].content;
						if(i<length-1)
							html += '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
					}
					html += '</font>';
					return html;
		        }
	    	},{
		        title: '操作',
		        formatter : function(value,row,index){
		        	var r = '<a class="fa fa-check-square-o btn btn-info" title="选择插入" onclick="loadBlank('+row.id+')">选择</a>';
		        	return r;
				}
		        }
	    	]
	      
	});
}
function showExplanationTable(){
	// 解答题加载表格
	$('#explanationTable').bootstrapTable({
		url:'expl/findRealPage', // 服务器数据的加载地址
		method: 'get',  
	    dataType: "json",  
	    striped: true,// 设置为 true 会有隔行变色效果
	    undefinedText: "空",// 当数据为 undefined 时显示的字符
	    pagination: true, // 分页
	    toolbar: '#toolbar',
	   // paginationLoop:true,//设置为 true 启用分页条无限循环的功能。
	    // showToggle: "true",//是否显示 切换试图（table/card）按钮
	    // showColumns: "true",//是否显示 内容列下拉框
	    showRefresh: true,// 是否显示刷新按钮
	    pageNumber: 1,// 如果设置了分页，首页页码
	    // showPaginationSwitch:true,//是否显示 数据条数选择框
	    pageSize: 6,// 如果设置了分页，页面数据条数
	    // pageList: [5, 10, 20, 40], //如果设置了分页，设置可供选择的页面数据条数。设置为All 则显示所有记录。
	    paginationPreText: '‹',// 指定分页条中上一页按钮的图标或文字,这里是<
	    paginationNextText: '›',// 指定分页条中下一页按钮的图标或文字,这里是>
	    // singleSelect: false,//设置True 将禁止多选
	    // search: true, //显示搜索框
	    data_local: "zh-US",// 表格汉化
	    sidePagination: "server", // 服务端处理分页
	    queryParams: function (params) {
	        return {
				page:(params.offset)/(params.limit)+1,
	            limit: params.limit,
	            sort:params.sort,
	            dir:params.order
	        };
	    },
	    idField: "id",// 指定主键列
	    columns: [
	    	{
	    		field:'id',
	    		title:'ID'
	    	},
	    	{
		        title: '题目',
		        formatter: function(value,row,index){
		        	var html = '<div class="quest-title-display">'+row.title+'</div>';
					html += "<font color=\"red\">参考答案:</font>"+row.reference.content;
	    			return html;
	    		}
	    	},{
		        title: '操作',
		        formatter : function(value,row,index){
		        	var r = '<a class="fa fa-check-square-o btn btn-info" title="选择插入" onclick="loadExplanation('+row.id+')">选择</a>';
		        	return r;
	        	}
			}
	    	]
	      
	});
}
function showSynthesizedTable(){
	
}
/*-------------------*/
/*选择单选题*/
function loadSingle(id){
	var _focus = $('.topics-focus');
	var _index;
	var _top_index = currentTopicsIndex();
	var _topics;
	if(isTopics(_focus)){
		_index = parseInt($(_focus).find('.paper-subtopics-item').length)+1;
	}else if(isSubtopics(_focus)){
		_topics = $(_focus).parents('.paper-topics-item');
		_index = currentSubtopicsIndex();
	}else{
		
	}
	
	$.ajax({
		url:'single/findOne',
		type:'post',
		dataType:'json',
		data:{id:id},
		success:function(data){
			if(data!=null){
				if(isQuExist(data.id,'Single')){
					alert("题目已存在！");
					return;
				}
				var html = "";
				html += '<div class="paper-subtopics-item">'+
							'<input type="hidden" class="question-id" value='+data.id+'>'+
							'<input type="hidden" class="question-num" value='+data.num+'>'+
							'<input type="hidden" class="question-type" value="Single">'+
							'<input type="hidden" class="subtopics-index-value" value='+_index+'>'+
							'<div class="paper-subtopics-index"><span>'+_index+'</span>、</div>'+
							'<div class="paper-subtopics-title" contenteditable="true">'+
								data.title+
							'</div>'+
							'<font color="blue"><i>(单选题)</i></font>'+
							'<div class="paper-subtopics-body">';
				var _answer = "";
				var length = Object.keys(data.options).length;
				for(var i=0;i<length;i++){
					
					html += '<div class="subtopics-options-item">'+
								'<input type="hidden" class="question-options-id" value='+data.options[optionsKey[i+1]].id+'>'+
								'<input type="hidden" class="question-options-num" value='+data.options[optionsKey[i+1]].num+'>'+
								'<div class="question-options-index">';
								if(data.answer.id==data.options[optionsKey[i+1]].id){
									_answer = optionsKey[i+1];
									html += '<input checked ';
								}else{
									html += '<input ';
								}
					html += 'onchange="answerSingle(this)" type="radio" name="name_'+_top_index+'_'+_index+'"><span>'+optionsKey[i+1]+'</span>.</div>'+
								'<div class="question-options-content" contenteditable="true" >'+
									data.options[optionsKey[i+1]].content+
								'</div>'+
							'</div>';
				}
								
				html += '</div>'+
							'<div class="question-answer">参考答案：<font color="blue">'+_answer+'</font></div>'+
							'<div class="paper-subtopics-score">'+
								'<span>分值：</span><input value="" required onchange="_inputScore(this)" class="subtopics-score-input" onkeyup="value=value.replace(/[^\\d.]/g,\'\')" required type="text">'+
							'</div>'+
						'</div>';
				if(isTopics(_focus)){
					$(_focus).append(html);
					updateTopicsIndex();
				}else if(isSubtopics(_focus)){
					$(_focus).after(html);
					updateSubtopicsIndex(_topics);
				}else{
					
				}
				$('#quListModel').modal('hide');
			}
			else{
				alert("空数据！");
			}
		},
		error:function(){
			alert("请求数据出错!");
		}
	});
}
/*-------------------*/
/*选择多选题*/
function loadMultiple(id){
	var _focus = $('.topics-focus');
	var _index;
	var _top_index = currentTopicsIndex();
	var _topics;
	if(isTopics(_focus)){
		_index = parseInt($(_focus).find('.paper-subtopics-item').length)+1;
	}else if(isSubtopics(_focus)){
		_topics = $(_focus).parents('.paper-topics-item');
		_index = currentSubtopicsIndex();
	}else{
		
	}
	
	$.ajax({
		url:'multiple/findOne',
		type:'post',
		dataType:'json',
		data:{id:id},
		success:function(data){
			if(data!=null){
				if(isQuExist(data.id,'Multiple')){
					alert("题目已存在！");
					return;
				}
				var html = "";
				html += '<div class="paper-subtopics-item">'+
							'<input type="hidden" class="question-id" value='+data.id+'>'+
							'<input type="hidden" class="question-num" value='+data.num+'>'+
							'<input type="hidden" class="question-type" value="Multiple">'+
							'<input type="hidden" class="subtopics-index-value" value='+_index+'>'+
							'<div class="paper-subtopics-index"><span>'+_index+'</span>、</div>'+
							'<div class="paper-subtopics-title" contenteditable="true">'+
								data.title+
							'</div>'+
							'<font color="blue"><i>(多选题)</i></font>'+
							'<div class="paper-subtopics-body">';
				var _answer = "";
				var length = Object.keys(data.options).length;
				for(var i=0;i<length;i++){
					
					html += '<div class="subtopics-options-item">'+
								'<input type="hidden" class="question-options-id" value='+data.options[optionsKey[i+1]].id+'>'+
								'<input type="hidden" class="question-options-num" value='+data.options[optionsKey[i+1]].num+'>'+
								'<div class="question-options-index">';
					var k=0;
					for(;k<data.answers.length;k++){
						if(data.answers[k].id==data.options[optionsKey[i+1]].id)break;
					}
					
					if(k<data.answers.length){
						_answer += optionsKey[i+1];
						html += '<input checked ';
					}else{
						html += '<input ';
					}
					
					html += 'onchange="answerSingle(this)" type="checkbox" name="name_'+_top_index+'_'+_index+'"><span>'+optionsKey[i+1]+'</span>.</div>'+
								'<div class="question-options-content" contenteditable="true" >'+
									data.options[optionsKey[i+1]].content+
								'</div>'+
							'</div>';
				}
								
				html += '</div>'+
							'<div class="question-answer">参考答案：<font color="blue">'+_answer+'</font></div>'+
							'<div class="paper-subtopics-score">'+
								'<span>分值：</span><input value="" required onchange="_inputScore(this)" class="subtopics-score-input" onkeyup="value=value.replace(/[^\\d.]/g,\'\')" required type="text">'+
							'</div>'+
						'</div>';
				if(isTopics(_focus)){
					$(_focus).append(html);
					updateTopicsIndex();
				}else if(isSubtopics(_focus)){
					$(_focus).after(html);
					updateSubtopicsIndex(_topics);
				}else{
					
				}
				$('#quListModel').modal('hide');
			}
			else{
				alert("空数据！");
			}
		},
		error:function(){
			alert("请求数据出错!");
		}
	});
}
/*-------------------*/
/*选择判断题*/
function loadJudgment(id){
	var _focus = $('.topics-focus');
	var _index;
	var _top_index = currentTopicsIndex();
	var _topics;
	if(isTopics(_focus)){
		_index = parseInt($(_focus).find('.paper-subtopics-item').length)+1;
	}else if(isSubtopics(_focus)){
		_topics = $(_focus).parents('.paper-topics-item');
		_index = currentSubtopicsIndex();
	}else{
		
	}
	
	$.ajax({
		url:'judgment/findOne',
		type:'post',
		dataType:'json',
		data:{id:id},
		success:function(data){
			if(data!=null){
				if(isQuExist(data.id,'Judgment')){
					alert("题目已存在！");
					return;
				}
				var html = "";
				html += '<div class="paper-subtopics-item">'+
							'<input type="hidden" class="question-id" value='+data.id+'>'+
							'<input type="hidden" class="question-id" value='+data.num+'>'+
							'<input type="hidden" class="question-type" value="Judgment">'+
							'<input type="hidden" class="subtopics-index-value" value='+_index+'>'+
							'<div class="paper-subtopics-index"><span>'+_index+'</span>、</div>'+
							'<div class="paper-subtopics-title" contenteditable="true">'+
								data.title+
							'</div>'+
							'<font color="blue"><i>(判断题)</i></font>'+
							'<div class="paper-subtopics-body">';
				var _answer = '';
				html += '<div class="paper-subtopics-body">'+
					'<div class="subtopics-options-item">';
				for(var i=0;i<data.options.length;i++){
					html += '<label>'+
								'<input type="hidden" class="question-options-id" value='+data.options[i].id+'>'+
								'<input type="hidden" class="question-options-num" value='+data.options[i].num+'>';
					if(data.answer.content==data.options[i].content)
						html += '<input checked ';
					else html += '<input ';
					html += 'value=true onchange="answerJudgment(this)" type="radio" name="name_'+_top_index+'_'+_index+'"><span>';
					if(data.options[i].content=='true')html +='正确';
					else html += '错误';
					html += '</span>&nbsp;&nbsp;</label>';	
				}
				if(data.answer.content=='true'){
					_answer = '<span class="fa fa-check"></span>';
				}else{
					_answer = '<span class="fa fa-close"></span>';
				}
						
				html += '</div>'+
				'</div>';
								
				html += '</div>'+
							'<div class="question-answer">参考答案：<font color="blue">'+_answer+'</font></div>'+
							'<div class="paper-subtopics-score">'+
								'<span>分值：</span><input value="" required onchange="_inputScore(this)" class="subtopics-score-input" onkeyup="value=value.replace(/[^\\d.]/g,\'\')" required type="text">'+
							'</div>'+
						'</div>';
				if(isTopics(_focus)){
					$(_focus).append(html);
					updateTopicsIndex();
				}else if(isSubtopics(_focus)){
					$(_focus).after(html);
					updateSubtopicsIndex(_topics);
				}else{
					
				}
				$('#quListModel').modal('hide');
			}
			else{
				alert("空数据！");
			}
		},
		error:function(){
			alert("请求数据出错!");
		}
	});
}
/*-------------------*/
/*选择填空题*/
function loadBlank(id){
	var _focus = $('.topics-focus');
	var _index;
	var _top_index = currentTopicsIndex();
	var _topics;
	if(isTopics(_focus)){
		_index = parseInt($(_focus).find('.paper-subtopics-item').length)+1;
	}else if(isSubtopics(_focus)){
		_topics = $(_focus).parents('.paper-topics-item');
		_index = currentSubtopicsIndex();
	}else{
		
	}
	
	$.ajax({
		url:'blank/findOne',
		type:'post',
		dataType:'json',
		data:{id:id},
		success:function(data){
			if(data!=null){
				if(isQuExist(data.id,'Blank')){
					alert("题目已存在！");
					return;
				}
				var html = "";
				html += '<div class="paper-subtopics-item">'+
							'<input type="hidden" class="question-id" value='+data.id+'>'+
							'<input type="hidden" class="question-id" value='+data.num+'>'+
							'<input type="hidden" class="question-type" value="Blank">'+
							'<input type="hidden" class="subtopics-index-value" value='+_index+'>'+
							'<div class="paper-subtopics-index"><span>'+_index+'</span>、</div>'+
							'<div onkeyup="divInputChange(this)" class="paper-subtopics-title" contenteditable="true">'+
								data.content+
							'</div>';
				html +=	'<font color="blue"><i>(填空题)</i></font>'+
						'<div class="paper-subtopics-body">';
				html += '</div>'+
							'<div class="question-answer">参考答案：<font color="blue"></font></div>'+
							'<div class="paper-subtopics-score">'+
								'<span>分值：</span><input value="" required onchange="_inputScore(this)" class="subtopics-score-input" onkeyup="value=value.replace(/[^\\d.]/g,\'\')" required type="text">'+
							'</div>'+
						'</div>';
				if(isTopics(_focus)){
					$(_focus).append(html);
					updateTopicsIndex();
					var _blank = $(_focus).find('.paper-subtopics-item').last();
					var inputList = $(_blank).find('.paper-subtopics-title input');
					var _answer = "";
					for(var i=0;i<inputList.length;i++){
						$(inputList[i]).val(data.blanks[i+1].content);
						_answer += '<span class="blank-reference"><input type="hidden" class="question-options-num" value='+data.blanks[i+1].num+'><input type="hidden" class="question-options-id" value='+data.blanks[i+1].id+'>'+data.blanks[i+1].content+'</span>';
					}
					$(_blank).find('.question-answer font').html(_answer);
				}else if(isSubtopics(_focus)){
					$(_focus).after(html);
					updateSubtopicsIndex(_topics);
					var _answer = "";
					var _blank = $(_focus).next('.paper-subtopics-item');
					var inputList = $(_blank).find('.paper-subtopics-title input');
					for(var i=0;i<inputList.length;i++){
						$(inputList[i]).val(data.blanks[i+1].content);
						_answer += '<span class="blank-reference"><input type="hidden" class="question-options-num" value='+data.blanks[i+1].num+'><input type="hidden" class="question-options-id" value='+data.blanks[i+1].id+'>'+data.blanks[i+1].content+'</span>';
					}
					$(_blank).find('.question-answer font').html(_answer);
				}else{
					
				}
				$('#quListModel').modal('hide');
			}
			else{
				alert("空数据！");
			}
		},
		error:function(){
			alert("请求数据出错!");
		}
	});
}
/*-------------------*/
/*选择解答题*/
function loadExplanation(id){
	var _focus = $('.topics-focus');
	var _index;
	var _top_index = currentTopicsIndex();
	var _topics;
	if(isTopics(_focus)){
		_index = parseInt($(_focus).find('.paper-subtopics-item').length)+1;
	}else if(isSubtopics(_focus)){
		_topics = $(_focus).parents('.paper-topics-item');
		_index = currentSubtopicsIndex();
	}else{
		
	}
	
	$.ajax({
		url:'expl/findOne',
		type:'post',
		dataType:'json',
		data:{id:id},
		success:function(data){
			if(data!=null){
				if(isQuExist(data.id,'Explanation')){
					alert("题目已存在！");
					return;
				}
				var html = "";
				html += '<div class="paper-subtopics-item">'+
							'<input type="hidden" class="question-id" value='+data.id+'>'+
							'<input type="hidden" class="question-num" value='+data.num+'>'+
							'<input type="hidden" class="question-type" value="Explanation">'+
							'<input type="hidden" class="subtopics-index-value" value='+_index+'>'+
							'<div class="paper-subtopics-index"><span>'+_index+'</span>、</div>'+
							'<div class="paper-subtopics-title" contenteditable="true">'+
								data.title+
							'</div>'+
							'<font color="blue"><i>(解答题)</i></font>'+
							'<div class="paper-subtopics-body">'+
							'</div>';			
				html += '<div class="question-answer">参考答案：'+
							'<input type="hidden" class="question-options-id" value='+data.reference.id+'>'+
							'<input type="hidden" class="question-options-num" value='+data.reference.num+'>'+
							'<div class="question-options-content" contenteditable="true">'+data.reference.content+'</div>'+
						'</div>'+
						'<div class="paper-subtopics-score">'+
							'<span>分值：</span><input value="" required onchange="_inputScore(this)" class="subtopics-score-input" onkeyup="value=value.replace(/[^\\d.]/g,\'\')" required type="text">'+
						'</div>'+
					'</div>';
				if(isTopics(_focus)){
					$(_focus).append(html);
					updateTopicsIndex();
				}else if(isSubtopics(_focus)){
					$(_focus).after(html);
					updateSubtopicsIndex(_topics);
				}else{
					
				}
				$('#quListModel').modal('hide');
			}
			else{
				alert("空数据！");
			}
		},
		error:function(){
			alert("请求数据出错!");
		}
	});
}
/*-------------------*/
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*试卷save提交保存*/

$("#paper_form222").submit(function(envent){
	if($('.paper-subtopics-item').length<=0){
		alert("题目不能为空！");
		return false;
	}else if(true){
		var id = $('#paper_id').val();
		var num = $('#paper_num').text();
		var description = $('#paper_desc').text();
		var subject_id = $("#slpk").find("option:selected").val();
		var paper_type = $("input[name='paperType']:checked").val();
		var comb_type = "Manual";
		var paper_time = $("#paper_time").text();
		
		var total_score = parseFloat(0);
		
		var data = {//Paper对象
				'id':id,
				'num':num,
				'description':description,
				'subject':{'id':subject_id},
				'paperType':paper_type,
				'combType':comb_type,
				'time':paper_time
				};
		
		
		
		var topicsList = $('.paper-topics-item');
		for(var i=0;i<topicsList.length;i++){
			//遍历大题
			alert('topics')
			var topics = {};//Topics对象
			
			var topics_id = $(topicsList[i]).find('.topics-id').val();
			var topics_index = $(topicsList[i]).find('.topics-index-value').val();
			var topics_title = $(topicsList[i]).find('.paper-topics-title').html();
			var is_compreh = false;
			if($(topicsList[i]).find('.topics-synthesized').length>0){
				is_compreh = true;
			}else{
				is_compreh = false;
			}
			$(topics).attr(topics_index,{
				'id':topics_id,
				'_index':topics_index,
				'title':topics_title,
				'isCompreh':is_compreh
			});
			
			var subTopicsList = $(topicsList[i]).find('.paper-subtopics-item');
			for(var k=0;k<subTopicsList.length;k++){
				//遍历小题
				alert('k'+k)
				var subtopics = {};//小题subtopics的Map对象
				
				var subtopics_id = $(subTopicsList[k]).find('.subtopics-id').val();
				var subtopics_index = $(subTopicsList[k]).find('.subtopics-index-value').val();
				var subtopics_score = $(subTopicsList[k]).find('.subtopics-score-input').val();
				total_score += subtopics_score;
				alert('subtopics_msg')
				var qu_type = $(subTopicsList[k]).find('.question-type').val();
				alert('qu_type')
				var question_id = $(subTopicsList[k]).find('.question-id').val();
				alert('question_id')
				var question_num = "";
				alert($(subTopicsList[k]).find('.question-num').length)
				if($(subTopicsList[k]).find('.question-num').length==1){
					
					question_num = $(subTopicsList[k]).find('.question-num').val();
					alert(66)
				}else{
					alert(65)
					question_num = new Date().getTime();
					alert(77)
				}
				alert('question_num')
				var is_compreh = false;
				if($(subTopicsList[k]).parents('.topics-synthesized').length>0)is_compreh = true;
				var question_title = $(subTopicsList[k]).find('.paper-subtopics-title').html();
				alert('question_title')
				var question = {
						'id':question_id,
						'num':question_num,
						'isCompreh':is_compreh,
						'title':question_title,
						'subject':{'id':subject_id}
						};
				alert('question_msg')
				if(qu_type=="Single"){
					//private Map<String, Options> options = new HashMap<String, Options>();
					//private Options answer;
					
					alert('single');
					var options = {};
					
					var optionsList = $(subTopicsList[k]).find('.subtopics-options-item');
					var _answer = {};
					
					//构建选项
					for(var h=0;h<optionsList.length;h++){
						//遍历选项
						var options_id = $(optionsList[h]).find('.question-options-id').val();
						var options_num = $(optionsList[h]).find('.question-options-num').val();
						
						if(options_num==""||options_num==null)
							options_num=new Date().getTime();
						
						var options_content = $(optionsList[h]).find('.question-options-content').html();
						var options_key = $(optionsList[h]).find('.question-options-index span').text();
						
						var option = {
								'id':options_id,
								'num':options_num,
								'content':options_content,
								};
						
						if($(optionsList[h]).find('input[type="radio"]:checked').length>0){
							_answer = {
									'id':options_id,
									'num':options_num,
									'content':options_content,
									};
						}
						
						$(options).attr(options_key,option);
					}
					
					$(question).attr('options',options);
					$(question).attr('answer',_answer);
					
					$(subtopics).attr('Single',question);
					
				}else if(qu_type=="Multiple"){
					alert('single');
					/*private Map<String, Options> options = new HashMap<String, Options>();
					private Set<Options> answers = new HashSet<Options>();*/
					var options = {};	
					var optionsList = $(subTopicsList[k]).find('.subtopics-options-item');
					var _answer = new Array();
					for(var h=0;h<optionsList.length;h++){
						//多选题遍历选项
						var options_id = $(optionsList[h]).find('.question-options-id').val();
						var options_num = $(optionsList[h]).find('.question-options-num').val();
						
						if(options_num==""||options_num==null)
							options_num=new Date().getTime();
						
						var options_content = $(optionsList[h]).find('.question-options-content').html();
						var options_key = $(optionsList[h]).find('.question-options-index span').text();
						
						var option = {
								'id':options_id,
								'num':options_num,
								'content':options_content,
								};
						if($(optionsList[h]).find('input[type="checkbox"]:checked').length>0){
							_answer.push({
								'id':options_id,
								'num':options_num,
								'content':options_content,
								});
						}
						$(options).attr(options_key,option);
					}
					$(question).attr('options',options);
					$(question).attr('answers',_answer);
					
					$(subtopics).attr('Multiple',question);
					
				}else if(qu_type=="Judgment"){
					/*
					private Set<Options> options = new HashSet<Options>();
					private Options answer;*/
					var options = new Array();
					var _answer = {};
					var optionsList = $(subTopicsList[k]).find('input[type="radio"]');
					for(var h=0;h<optionsList.length;h++){
						var option_id = $(optionsList[h]).siblings('.question-options-id').val();
						var option_content = $(optionsList[h]).val();
						
						var options_num = $(optionsList[h]).find('.question-options-num').val();
						if(options_num==""||options_num==null)
							options_num=new Date().getTime();
						
						options.push({
							'id':option_id,
							'num':options_num,
							'content':option_content
							});
						
						if($(optionsList[h]).attr('checked'))
							_answer = {
									'id':option_id,
									'num':options_num,
									'content':option_content
									};
					}
					$(question).attr('options',options);
					$(question).attr('answer',_answer);
					
					$(subtopics).attr('Judgment',question);
				}else if(qu_type=="Blank"){
					/*private Map<Integer, Options> blanks = new HashMap<Integer, Options>();*/
					var blanks = {};
					var inputList = $(subTopicsList[k]).find('.paper-subtopics-title input');
					for(var h=0;h<inputList.length;h++){
						var option_content = $(inputList[h]).val();
						$(blanks).attr((h+1),{'content':option_content});
					}
					$(question).attr('blanks',blanks);
					
					$(subtopics).attr('Blank',question);
					
				}else if(qu_type=="Explanation"){
					/*
					private Options reference;*/
					
					var option_id = $(subTopicsList[k]).find('.question-answer .question-options-id').val();
					var option_num = $(subTopicsList[k]).find('.question-answer .question-options-num').val();
					var option_content = $(subTopicsList[k]).find('.question-options-content').html();
					
					var reference = {
							'id':option_id,
							'num':option_num,
							'content':option_content,
							};
					
					$(question).attr('reference',reference);
					
					$(subtopics).attr('Explanation',question);
				}else {
					
				}
				$(topics).attr(subtopics_index,subtopics);
			}
			
			$(data).attr(topics_index,topics);
		}
		
		var result = JSON.stringify(data);//string类型
		alert(result);
		//ajax请求保存paper
		alert('ajax')
		$.ajax({
			url:'paper/save',
			type:'post',
			dataType:'json',
			data:{paper:result},
			success:function(data){
				alert(data.msg);
				if(data.succcess){
					
				}
			},
			error:function(){
				alert('出错!');
			}
		})
		return false;
	}else{
		alert("内容不能留空!")
		return false;
	}
	return false;
});

$('#paper_form').submit(function(event){
	if($('.paper-subtopics-item').length<=0){
		alert("题目不能为空！");
		return false;
	}else if(validatePaper()){//validatePaper()
		var id = $('#paper_id').val();
		var num = $('#paper_num').text();
		var title = $('#paper_title').text();
		var description = $('#paper_desc').text();
		var subject_id = $('#paper_subject').val();
		var paper_type = $("input[name='paper_type']:checked").val();
		var comb_type = "Manual";
		var paper_time = $("#paper_time").text();
		
		var total_score = parseFloat(0);
		
		var data = {//Paper对象
				'id':id,
				'title':title,
				'num':num,
				'description':description,
				'subject':{'id':subject_id},
				'paperType':paper_type,
				'combType':comb_type,
				'time':paper_time
				};
		
		
		
		var topicsList = $('.paper-topics-item');
		var topics = {};
		for(var i=0;i<topicsList.length;i++){
			//遍历大题
			var topic = {};//Topics对象
			
			var topics_id = $(topicsList[i]).find('.topics-id').val();
			var topics_index = $(topicsList[i]).find('.topics-index-value').val();
			var topics_title = $(topicsList[i]).find('.paper-topics-title').html();
			var is_compreh = false;
			if($(topicsList[i]).find('.topics-synthesized').length>0){
				is_compreh = true;
			}else{
				is_compreh = false;
			}
			topic = {
				'id':topics_id,
				'_index':topics_index,
				'title':topics_title,
				'compreh':is_compreh
			};
			var subtopics = {};
			var subTopicsList = $(topicsList[i]).find('.paper-subtopics-item');
			for(var k=0;k<subTopicsList.length;k++){
				//遍历小题
				var subtopic = {};//小题subtopics的Map对象
				
				var subtopics_id = $(subTopicsList[k]).find('.paper-subtopics-id').val();
				var subtopics_index = $(subTopicsList[k]).find('.subtopics-index-value').val();
				var subtopics_score = parseFloat($(subTopicsList[k]).find('.subtopics-score-input').val());
				total_score += subtopics_score;
				
				subtopic = {
						'id':subtopics_id,
						'_index':subtopics_index,
						'score':subtopics_score
						};
				
				var qu_type = $(subTopicsList[k]).find('.question-type').val();

				var question_id = $(subTopicsList[k]).find('.question-id').val();
				var question_num = "";
				if($(subTopicsList[k]).find('.question-num')==1){
					question_num = $(subTopicsList[k]).find('.question-num').val();
				}else{
					question_num = newGuid();
				}
				var is_compreh = false;
				if($(subTopicsList[k]).parents('.topics-synthesized').length>0)is_compreh = true;
				var question_title = $(subTopicsList[k]).find('.paper-subtopics-title').html();
				
				var question = {
						'id':question_id,
						'num':question_num,
						'compreh':is_compreh,
						'title':question_title,
						'subject':{'id':subject_id}
						};
				
				if(qu_type=="Single"){
					//private Map<String, Options> options = new HashMap<String, Options>();
					//private Options answer;
					
					
					var options = {};
					
					var optionsList = $(subTopicsList[k]).find('.subtopics-options-item');
					var _answer = {};
					
					//构建选项
					for(var h=0;h<optionsList.length;h++){
						//遍历选项
						var options_id = $(optionsList[h]).find('.question-options-id').val();
						var options_num = $(optionsList[h]).find('.question-options-num').val();
						
						if(options_num==""||options_num==null)
							options_num = newGuid();
						
						var options_content = $(optionsList[h]).find('.question-options-content').html();
						var options_key = $(optionsList[h]).find('.question-options-index span').text();
						
						var option = {
								'id':options_id,
								'num':options_num,
								'content':options_content,
								};
						
						if($(optionsList[h]).find('input[type="radio"]:checked').length>0){
							_answer = {
									'id':options_id,
									'num':options_num,
									'content':options_content,
									};
						}
						
						$(options).attr(options_key,option);
					}
					
					$(question).attr('options',options);
					$(question).attr('answer',_answer);
					
					$(subtopic).attr('single',question);
					
					$(subtopics).attr(subtopics_index,subtopic);
					
				}else if(qu_type=="Multiple"){
					/*private Map<String, Options> options = new HashMap<String, Options>();
					private Set<Options> answers = new HashSet<Options>();*/
					var options = {};	
					var optionsList = $(subTopicsList[k]).find('.subtopics-options-item');
					var _answer = new Array();
					for(var h=0;h<optionsList.length;h++){
						//多选题遍历选项
						var options_id = $(optionsList[h]).find('.question-options-id').val();
						var options_num = $(optionsList[h]).find('.question-options-num').val();
						
						if(options_num==""||options_num==null)
							options_num = newGuid();
						
						var options_content = $(optionsList[h]).find('.question-options-content').html();
						var options_key = $(optionsList[h]).find('.question-options-index span').text();
						
						var option = {
								'id':options_id,
								'num':options_num,
								'content':options_content,
								};
						if($(optionsList[h]).find('input[type="checkbox"]:checked').length>0){
							_answer.push({
								'id':options_id,
								'num':options_num,
								'content':options_content,
								});
						}
						$(options).attr(options_key,option);
					}
					$(question).attr('options',options);
					$(question).attr('answers',_answer);
					
					$(subtopic).attr('multiple',question);
					$(subtopics).attr(subtopics_index,subtopic);
					
				}else if(qu_type=="Judgment"){
					/*
					private Set<Options> options = new HashSet<Options>();
					private Options answer;*/
					var options = new Array();
					var _answer = {};
					
					var optionsList = $(subTopicsList[k]).find('input[type="radio"]');
					for(var h=0;h<optionsList.length;h++){
						var option_id = $(optionsList[h]).siblings('.question-options-id').val();
						var option_content = $(optionsList[h]).val();
						
						var options_num = $(optionsList[h]).siblings('.question-options-num').val();
						if(options_num==""||options_num==null)
							options_num= newGuid();
						options.push({
							'id':option_id,
							'num':options_num,
							'content':option_content
							});
						
						if($(optionsList[h]).prop('checked')){
							_answer = {
									'id':option_id,
									'num':options_num,
									'content':option_content
									};
						}
					}
					$(question).attr('options',options);
					$(question).attr('answer',_answer);
					
					$(subtopic).attr('judgment',question);
					$(subtopics).attr(subtopics_index,subtopic);
				}else if(qu_type=="Blank"){
					/*private Map<Integer, Options> blanks = new HashMap<Integer, Options>();*/
					var blanks = {};
					var inputList = $(subTopicsList[k]).find('.paper-subtopics-title input');
					for(var h=0;h<inputList.length;h++){
						var option_content = $(inputList[h]).val();
						var option_id = $(inputList[h]).data('option_id');
						var option_num = $(inputList[h]).data('option_num');
						if(option_num==""||option_num==null){
							option_num = newGuid();
						}
						$(blanks).attr((h+1),{'id':option_id,'num':option_num,'content':option_content});
					}
					$(question).attr('blanks',blanks);
					
					$(subtopic).attr('blank',question);
					$(subtopics).attr(subtopics_index,subtopic);
					
				}else if(qu_type=="Explanation"){
					/*
					private Options reference;*/
					
					var option_id = $(subTopicsList[k]).find('.question-answer .question-options-id').val();
					var option_num = $(subTopicsList[k]).find('.question-answer .question-options-num').val();
					if(option_num==""||option_num==null)option_num = newGuid();
					var option_content = $(subTopicsList[k]).find('.question-options-content').html();
					
					var reference = {
							'id':option_id,
							'num':option_num,
							'content':option_content,
							};
					
					$(question).attr('reference',reference);
					
					$(subtopic).attr('explanation',question);
				}else {
					
				}
				$(topic).attr('subtopics',subtopics);
				$(subtopics).attr(subtopics_index,subtopic);
			}

			$(topics).attr(topics_index,topic);
		}
		$(data).attr('topics',topics);
		$(data).attr('score',total_score);
		
		var result = JSON.stringify(data);//string类型
		
		console.log(result);
		//ajax请求保存paper
		$.ajax({
			url:'paper/save',
			type:'post',
			dataType:'json',
			data:{paper:result},
			success:function(data){
				alert(data.msg);
				if(data.succcess){
					
				}
			},
			error:function(){
				alert('出错!');
			}
		});
		return false;
	}else{
		alert("内容不能留空!")
		return false;
	}
	return false;
});
//验证div框输入
function validatePaper(){
	//1去除原input-required提示不能为空的样式
	var requiredList = $('.input-required');
	for(var i=0;i<requiredList.length;i++){
		$(requiredList[i]).removeClass('input-required');
	}
	//2验证div输入框
	var paperMsgList = $('.paper-msg-content');
	for(var i=0;i<paperMsgList.length;i++){
		if(isInputEmpty(paperMsgList[i])){
			$(paperMsgList[i]).addClass('input-required');
		}
	}
	var topicsTitleList = $('.paper-topics-title');
	for(var i=0;i<topicsTitleList.length;i++){
		if(isInputEmpty(topicsTitleList[i])){
			$(topicsTitleList[i]).addClass('input-required');
		}
	}
	var subtopicsTitleList = $('.paper-subtopics-title');
	for(var i=0;i<subtopicsTitleList.length;i++){
		if(isInputEmpty(subtopicsTitleList[i])){
			$(subtopicsTitleList[i]).addClass('input-required');
		}
	}
	var optionList = $('.question-options-content');
	for(var i=0;i<optionList.length;i++){
		if(isInputEmpty(optionList[i])){
			$(optionList[i]).addClass('input-required');
		}
	}
	if($('.input-required').length>0){
		return false;
	}else if($('.paper-subtopics-item').length<=0){
		return false;
	}else{
		return true;
	}
}
/*-------------------*/

/*加载试卷*/
function loadPaper(id){
	if(id!=""&&id!=null){
		$.ajax({
			url:'paper/findOne',
			type:'post',
			dataType:'json',
			data:{id:id},
			success:function(data){
				if(data==null){
					alert("空数据!");
				}else{
					//加载试卷信息
					var titleHtml = "";
					var bodyHtml = "";
					
					//试卷头基本信息
					titleHtml += '<input type="hidden" id="paper_id" value='+data.id+'>'+
					'<div class="question-options-index"style="float:left;" >&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;标题：</div><div id="paper_title" class="paper-msg-content" style="overflow:hidden;" contenteditable="true">'+data.title+'</div>'+
					'<div class="question-options-index" style="float:left;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;编号：</div><div id="paper_num" class="paper-msg-content" style="overflow:hidden;" contenteditable="true">'+data.num+'</div>'+
					'<div class="question-options-index" style="float:left;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;描述：</div><div id="paper_desc" class="paper-msg-content" style="overflow:hidden;" contenteditable="true">'+data.description+'</div>'+
					'<div class="question-options-index" style="float:left;">考试时长：</div><div id="paper_time" class="paper-msg-content" style="overflow:hidden;" contenteditable="true">'+data.time+'</div>'+
					'<div class="question-options-index" style="float:left;">试卷类型：</div>'+
					'<div id="paper_type" style="overflow:hidden;">';
					if(data.paperType=='Formal'){
						titleHtml += '<label><input required type="radio" name="paper_type" value="Exercise">练习卷</label>'+
										'<label><input checked type="radio" name="paper_type" value="Formal">正式卷</label>';
					}else{
						titleHtml += '<label><input checked required type="radio" name="paper_type" value="Exercise">练习卷</label>'+
									'<label><input type="radio" name="paper_type" value="Formal">正式卷</label>';
					}
					titleHtml += '</div>';
					var subject = "&nbsp;";
					if(data.subject!=null)subject = data.subject.name;
					titleHtml += '<div class="question-options-index" style="float:left;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;科目：</div><input type="hidden"  id="paper_subject" value=""><div style="overflow:hidden;">'+subject+'</div>';
					var _teacher = "&nbsp;";
					if(data.teacher!=null){
						for(var i=0;i<data.teacher.length;i++){
							_teacher += data.teacher[i].name;
							if(i!=0&&i!=data.teacher.length)_teacher+=',';
						}
					}
					titleHtml += '<div id="paper_teacher" class="question-options-index" style="float:left;">组卷教师：</div><div style="overflow:hidden;">'+_teacher+'</div>'+
					'<div id="paper_score" class="question-options-index">试卷总分：</div><div style="overflow:hidden;"><span>'+data.score+'</span></div>';
					//试卷body信息  
					var topics_length = Object.keys(data.topics).length;
					console.log(topics_length)
					for(var i=0;i<topics_length;i++){
						//遍历大题
						bodyHtml += '<div class="paper-topics-item">'+
							'<input type="hidden" class="topics-id" value='+data.topics[i+1].id+'>'+
							'<input type="hidden" class="topics-index-value" value='+data.topics[i+1]._index+'>'+
							'<div class="paper-topics-index"><span>'+getTopicsIndex(data.topics[i+1]._index)+'</span>、</div>'+
							'<div class="paper-topics-title" contenteditable="true">'+data.topics[i+1].title+'</div>'+
							'<font class="paper-topics-score" color="blue"><i>(总分：<span></span>)</i></font>';
						var subtopics_length = Object.keys(data.topics[i+1].subtopics).length;
						console.log('subtopicslength'+subtopics_length)
						for(var j=0;j<subtopics_length;j++){
							var question_type = "";
								if(data.topics[i+1].subtopics[j+1].single!=null){
									//单选题
									var single = data.topics[i+1].subtopics[j+1].single;
									bodyHtml += '<div class="paper-subtopics-item">'+
												'<input type="hidden" class="paper-subtopics-id" value='+data.topics[i+1].subtopics[j+1].id+'>'+
												'<input type="hidden" class="question-id" value='+single.id+'>'+
												'<input type="hidden" class="question-num" value='+single.num+'>'+
												'<input type="hidden" class="question-type" value="Single">'+
												'<input type="hidden" class="subtopics-index-value" value='+data.topics[i+1].subtopics[j+1]._index+'>'+
												'<div class="paper-subtopics-index"><span>'+data.topics[i+1].subtopics[j+1]._index+'</span>、</div>'+
												'<div class="paper-subtopics-title" contenteditable="true">'+
													single.title+
												'</div>'+
												'<font color="blue"><i>(单选题)</i></font>'+
												'<div class="paper-subtopics-body">';
									var _answer = "";
									var length = Object.keys(single.options).length;
									for(var h=0;h<length;h++){
										
										bodyHtml += '<div class="subtopics-options-item">'+
													'<input type="hidden" class="question-options-id" value='+single.options[optionsKey[h+1]].id+'>'+
													'<input type="hidden" class="question-options-num" value='+single.options[optionsKey[h+1]].num+'>'+
													'<div class="question-options-index">';
													if(single.answer.id==single.options[optionsKey[h+1]].id){
														_answer = optionsKey[h+1];
														bodyHtml += '<input checked ';
													}else{
														bodyHtml += '<input ';
													}
										bodyHtml += 'onchange="answerSingle(this)" type="radio" name="name_'+data.topics[i+1]._index+'_'+data.topics[i+1].subtopics[j+1]._index+'"><span>'+optionsKey[h+1]+'</span>.</div>'+
													'<div class="question-options-content" contenteditable="true" >'+
														single.options[optionsKey[h+1]].content+
													'</div>'+
												'</div>';
									}
													
									bodyHtml += '</div>'+
												'<div class="question-answer">参考答案：<font color="blue">'+_answer+'</font></div>'+
												'<div class="paper-subtopics-score">'+
													'<span>分值：</span><input value="'+data.topics[i+1].subtopics[j+1].score+'" required onchange="_inputScore(this)" class="subtopics-score-input" onkeyup="value=value.replace(/[^\\d.]/g,\'\')" required type="text">'+
												'</div>'+
											'</div>';
								}else if(data.topics[i+1].subtopics[j+1].multiple!=null){
									//多选题
									var multiple = data.topics[i+1].subtopics[j+1].multiple;
									bodyHtml += '<div class="paper-subtopics-item">'+
									'<input type="hidden" class="paper-subtopics-id" value='+data.topics[i+1].subtopics[j+1].id+'>'+
										'<input type="hidden" class="question-id" value='+multiple.id+'>'+
										'<input type="hidden" class="question-num" value='+multiple.num+'>'+
										'<input type="hidden" class="question-type" value="Multiple">'+
										'<input type="hidden" class="subtopics-index-value" value='+data.topics[i+1].subtopics[j+1]._index+'>'+
										'<div class="paper-subtopics-index"><span>'+data.topics[i+1].subtopics[j+1]._index+'</span>、</div>'+
										'<div class="paper-subtopics-title" contenteditable="true">'+
											multiple.title+
										'</div>'+
										'<font color="blue"><i>(多选题)</i></font>'+
										'<div class="paper-subtopics-body">';
										var _answer = "";
										var length = Object.keys(multiple.options).length;
										for(var h=0;h<length;h++){
							
											bodyHtml += '<div class="subtopics-options-item">'+
														'<input type="hidden" class="question-options-id" value='+multiple.options[optionsKey[h+1]].id+'>'+
														'<input type="hidden" class="question-options-num" value='+multiple.options[optionsKey[h+1]].num+'>'+
														'<div class="question-options-index">';
											var l=0;
											for(;l<multiple.answers.length;l++){
												if(multiple.answers[l].id==multiple.options[optionsKey[h+1]].id)break;
											}
											
											if(l<multiple.answers.length){
												_answer += optionsKey[h+1];
												bodyHtml += '<input checked ';
											}else{
												bodyHtml += '<input ';
											}
											
											bodyHtml += 'onchange="answerSingle(this)" type="checkbox" name="name_'+data.topics[i+1]._index+'_'+data.topics[i+1].subtopics[j+1]._index+'"><span>'+optionsKey[h+1]+'</span>.</div>'+
														'<div class="question-options-content" contenteditable="true" >'+
															multiple.options[optionsKey[h+1]].content+
														'</div>'+
													'</div>';
										}
										
										bodyHtml += '</div>'+
													'<div class="question-answer">参考答案：<font color="blue">'+_answer+'</font></div>'+
													'<div class="paper-subtopics-score">'+
														'<span>分值：</span><input value="'+data.topics[i+1].subtopics[j+1].score+'" value="" required onchange="_inputScore(this)" class="subtopics-score-input" onkeyup="value=value.replace(/[^\\d.]/g,\'\')" required type="text">'+
													'</div>'+
												'</div>';
								}else if(data.topics[i+1].subtopics[j+1].judgment!=null){
									//判断题
									var judgment = data.topics[i+1].subtopics[j+1].judgment;
									bodyHtml += '<div class="paper-subtopics-item">'+
												'<input type="hidden" class="paper-subtopics-id" value='+data.topics[i+1].subtopics[j+1].id+'>'+
												'<input type="hidden" class="question-id" value='+judgment.id+'>'+
												'<input type="hidden" class="question-id" value='+judgment.num+'>'+
												'<input type="hidden" class="question-type" value="Judgment">'+
												'<input type="hidden" class="subtopics-index-value" value='+data.topics[i+1].subtopics[j+1]._index+'>'+
												'<div class="paper-subtopics-index"><span>'+data.topics[i+1].subtopics[j+1]._index+'</span>、</div>'+
												'<div class="paper-subtopics-title" contenteditable="true">'+
												judgment.title+
												'</div>'+
												'<font color="blue"><i>(判断题)</i></font>'+
												'<div class="paper-subtopics-body">';
												var _answer = '';
												bodyHtml += '<div class="paper-subtopics-body">'+
													'<div class="subtopics-options-item">';
												for(var k=0;k<judgment.options.length;k++){
													bodyHtml += '<label>'+
																'<input type="hidden" class="question-options-id" value='+judgment.options[k].id+'>'+
																'<input type="hidden" class="question-options-num" value='+judgment.options[k].num+'>';
													if(judgment.answer.content==judgment.options[k].content)
														bodyHtml += '<input checked ';
													else bodyHtml += '<input ';
													
													bodyHtml += 'value=true onchange="answerJudgment(this)" type="radio" name="name_'+(data.topics[i+1])._index+'_'+data.topics[i+1].subtopics[j+1]._index+'"><span>';
													if(judgment.options[k].content=='true')bodyHtml +='正确';
													else bodyHtml += '错误';
													bodyHtml += '</span>&nbsp;&nbsp;</label>';	
												}
												if(judgment.answer.content=='true'){
													_answer = '<span class="fa fa-check"></span>';
												}else{
													_answer = '<span class="fa fa-close"></span>';
												}
														
												bodyHtml += '</div>'+
												'</div>';
																
												bodyHtml += '</div>'+
															'<div class="question-answer">参考答案：<font color="blue">'+_answer+'</font></div>'+
															'<div class="paper-subtopics-score">'+
																'<span>分值：</span><input value="'+data.topics[i+1].subtopics[j+1].score+'" required onchange="_inputScore(this)" class="subtopics-score-input" onkeyup="value=value.replace(/[^\\d.]/g,\'\')" required type="text">'+
															'</div>'+
														'</div>';
								}else if(data.topics[i+1].subtopics[j+1].blank!=null){
									//填空题
									var blank = data.topics[i+1].subtopics[j+1].blank;
										bodyHtml += '<div class="paper-subtopics-item">'+
													'<input type="hidden" class="paper-subtopics-id" value='+data.topics[i+1].subtopics[j+1].id+'>'+
													'<input type="hidden" class="question-id" value='+blank.id+'>'+
													'<input type="hidden" class="question-id" value='+blank.num+'>'+
													'<input type="hidden" class="question-type" value="Blank">'+
													'<input type="hidden" class="subtopics-index-value" value='+data.topics[i+1].subtopics[j+1]._index+'>'+
													'<div class="paper-subtopics-index"><span>'+data.topics[i+1].subtopics[j+1]._index+'</span>、</div>'+
													'<div onkeyup="divInputChange(this)" class="paper-subtopics-title" contenteditable="true">';
										
										var contentDOM = $('<body></body>');
										$(contentDOM).html(blank.title);
										console.log('blank的题干:'+$(contentDOM).html())
										var _answer = '';
										
										var blank_list = $(contentDOM).find('input');
										
										for(var x=0;x<blank_list.length;x++){
											console.log(blank.blanks[x+1])
											console.log($(blank_list[x]).attr('class'));
											$(blank_list[x]).val(blank.blanks[x+1].content);
											
											$(blank_list[x]).data('option_id',blank.blanks[x+1].id);
											$(blank_list[x]).data('option_num',blank.blanks[x+1].num);
											
											_answer += '<span class="blank-reference">'+blank.blanks[x+1].content+'</span>';
										}
										bodyHtml += $(contentDOM).html();
										
										console.log('blank的题干:'+$(contentDOM).html())
										
										bodyHtml +=	'</div>'+
												'<font color="blue"><i>(填空题)</i></font>'+
												'<div class="paper-subtopics-body">';
										bodyHtml += '</div>'+
													'<div class="question-answer">参考答案：<font color="blue">'+_answer+'</font></div>'+
													'<div class="paper-subtopics-score">'+
														'<span>分值：</span><input value="'+data.topics[i+1].subtopics[j+1].score+'" required onchange="_inputScore(this)" class="subtopics-score-input" onkeyup="value=value.replace(/[^\\d.]/g,\'\')" required type="text">'+
													'</div>'+
												'</div>';
								}else if(data.topics[i+1].subtopics[j+1].explanation!=null){
									//解答题
									var explanation = data.topics[i+1].subtopics[j+1].explanation;
									bodyHtml += '<div class="paper-subtopics-item">'+
												'<input type="hidden" class="paper-subtopics-id" value='+data.topics[i+1].subtopics[j+1].id+'>'+
												'<input type="hidden" class="question-id" value='+explanation.id+'>'+
												'<input type="hidden" class="question-num" value='+explanation.num+'>'+
												'<input type="hidden" class="question-type" value="Explanation">'+
												'<input type="hidden" class="subtopics-index-value" value='+data.topics[i+1].subtopics[j+1]._index+'>'+
												'<div class="paper-subtopics-index"><span>'+data.topics[i+1].subtopics[j+1]._index+'</span>、</div>'+
												'<div class="paper-subtopics-title" contenteditable="true">'+
													explanation.title+
												'</div>'+
												'<font color="blue"><i>(解答题)</i></font>'+
												'<div class="paper-subtopics-body">'+
												'</div>';			
									bodyHtml += '<div class="question-answer">参考答案：'+
												'<input type="hidden" class="question-options-id" value='+explanation.reference.id+'>'+
												'<input type="hidden" class="question-options-num" value='+explanation.reference.num+'>'+
												'<div class="question-options-content" contenteditable="true">'+explanation.reference.content+'</div>'+
											'</div>'+
											'<div class="paper-subtopics-score">'+
												'<span>分值：</span><input value="'+data.topics[i+1].subtopics[j+1].score+'" required onchange="_inputScore(this)" class="subtopics-score-input" onkeyup="value=value.replace(/[^\\d.]/g,\'\')" required type="text">'+
											'</div>'+
										'</div>';
								}else{
									
								}
						}
						bodyHtml += '</div>';
					}
					$('.edit-paper-title div').html(titleHtml);
					$('.edit-paper-body').html(bodyHtml);
					//
					updateLoadBlank();
					updateScore();
				}
			},
			error:function(){
				alert("空!");
			}
		});
	}else{
		alert("空id!");
	}
}
/*-------------------*/





















































function test(){
	/*var selObj = window.getSelection();
	//var result = JSON.stringify(sel);//string类型
	console.log(selObj.getRangeAt(0));
	var newNode = document.createElement("img");
	selObj.getRangeAt(0).insertNode(newNode);*/
	//$('#insertImgModal').modal('show');
	//alert($('.paper-subtopics-title ::after').length);
	//$('.paper-subtopics-title:after').prop('content','2154654');
	//$('html').fadeTo(200,0.5);
	//alert(new Date().getTime());
	var str = '<p><span></span></p><div><span></span></div>0000';
	var bodyObj = $('<body></body>');
	$(bodyObj).html(str);
	$(bodyObj).find('span').text('000');
	console.log($(bodyObj).html());
	var str2 = $(str);
	$(str2).find('span').text('000');
	console.log(str2.length)
	console.log(str2[1].outerHTML);
	console.log(str2[0].outerHTML);
	console.log(str2.outerHTML);
	$('body').append('<i>111<i>'+str.toString());
	
}

function testInsert(){
	if(window.getSelection){
		var se = window.getSelection();
		var start = se.anchorOffset;
		alert(start);
	}
}

function testCn(){
	var v = $('#testCn').val();
	alert(getTopicsIndex(v));
}
function inputScore(obj){
	var parent = $(obj).parents('.topic-item');
	var total = $(parent).find('.total-score');
	var inputs = $(parent).find('.subtopic-score');
	var totalScore = parseFloat(0);
	var ret = /^\d+(\.\d+)?$/;
	for(var i=0;i<inputs.length;i++){
		if(ret.test(inputs[i].value)){
			totalScore += parseFloat(inputs[i].value);
		}
	}
	$(total).text(totalScore);
}
function subTopicsWindow(id){
    	var openUrl = "subTopicList.jsp?id="+id;//弹出窗口的url
        var iHeight=window.screen.availHeight*0.8; //弹出窗口的宽度;
        var iWidth=window.screen.availWidth*0.9; //弹出窗口的高度;
        var iTop = (window.screen.availHeight-30-iHeight)/2; //获得窗口的垂直位置;
        var iLeft = (window.screen.availWidth-10-iWidth)/2; //获得窗口的水平位置;
        window.open(openUrl,"","height="+iHeight+", width="+iWidth+", top="+iTop+", left="+iLeft);
        return false
    }
function deleteTopic(obj){
	if(confirm("确定要移除该题目？")){
		$(obj).parents(".topic-item").remove();
	}
}
function addTopic(){
	var index = $(".topic-item").length+1;
	var id="topic-content"+index;
	var topicHtml = "<div class=\"col-sm-11 topic-item\">\r\n" + 
	"						<input type=\"hidden\" name=\"topoc_id\">\r\n" + 
	"						<div class=\"btn-group btn-group-sm pull-right\">\r\n" + 
	"						\r\n" + 
	"							<button onclick=\"subTopicsWindow('"+id+"')\" type=\"button\" class=\"btn btn-primary\" title=\"添加小题\"><span class=\"fa fa-plus\"></span></button>\r\n" + 
	"							<button onclick=\"deleteTopic(this)\" type=\"button\" class=\"btn btn-danger\" title=\"删除\"><span class=\"fa fa-close\"></span></button>\r\n" + 
	"						    <button type=\"button\" class=\"btn btn-default\" title=\"上移\"><span class=\"fa fa-arrow-up\"></span></button>&nbsp;\r\n" + 
	"						    <button type=\"button\" class=\"btn btn-default\" title=\"下移\"><span class=\"fa fa-arrow-down\"></span></button>&nbsp;\r\n" + 
	"						    \r\n" + 
	"						</div>\r\n" + 
	"						\r\n" +
	"						<div class=\"form-group\">\r\n" + 
	"							<label class=\"col-sm-1 control-label\">题干</label>\r\n" + 
	"							<div class=\"col-sm-9\">\r\n" + 
	"								<div class=\"input-group\">\r\n" + 
	"									<span class=\"input-group-addon\">"+index+"</span>\r\n" + 
	"									<input class=\"form-control\" type=\"text\" name=\"topic_title\" required/>\r\n" + 
	"								</div>\r\n" + 
	"							</div>\r\n" + 
	"						</div>\r\n" + 
	"						<div class=\"form-group\">\r\n" + 
	"							<label class=\"col-sm-1 control-label\">总分值:</label>\r\n" + 
	"							<div class=\"form-control-static total-score\" id=\"totalScore"+index+"\"></div>\r\n" + 
	"						</div>\r\n" + 
	"						\r\n" + 
	"						<div class=\"form-group\">\r\n" + 
	"							<div class=\"col-sm-offset-1 col-sm-9 topic-content\" id=\""+id+"\">\r\n" + 
	
	
	
									/*"<div class=\"subtopic-item\">"+
									"								<div class=\"input-group col-sm-2 pull-right\">\r\n" + 
									"									<span class=\"input-group-addon\">分值</span>\r\n" + 
									"									<input onkeyup=\"inputScore(this)\" class=\"form-control subtopic-score\" type=\"text\" name=\"subtopic_score\" required/>\r\n" + 
									"								</div>\r\n" +
	"								<!-- 小题ID隐藏域 -->\r\n" +
	"								<input type=\"hidden\" name=\"subtopic_id\">\r\n" + 
	"								\r\n" + 
	"								<!-- 小题内容 -->\r\n" + 
	"								<h4><span>1</span>.小题题目</h4>\r\n" + 
	"								<ul class=\"row list-style-none\">\r\n" + 
	"									<li class=\"col-sm-6\">\r\n" + 
	"										<label class=\"radio-inline\">\r\n" + 
	"											<input type=\"radio\" name=\"optionsRadiosinline\" id=\"\" value=\"\">A.选项 1\r\n" + 
	"										</label>\r\n" + 
	"									</li>\r\n" + 
	"									<li class=\"col-sm-6\">\r\n" + 
	"										<label class=\"radio-inline\">\r\n" + 
	"											<input type=\"radio\" name=\"optionsRadiosinline\" id=\"\" value=\"\">B.选项 1\r\n" + 
	"										</label>\r\n" + 
	"									</li>\r\n" + 
	"									<li class=\"col-sm-6\">\r\n" + 
	"										<label class=\"radio-inline\">\r\n" + 
	"											<input type=\"radio\" name=\"optionsRadiosinline\" id=\"\" value=\"\">C.选项 1\r\n" + 
	"										</label>\r\n" + 
	"									</li>\r\n" + 
	"									<li class=\"col-sm-6\">\r\n" + 
	"										<label class=\"radio-inline\">\r\n" + 
	"											<input type=\"radio\" name=\"optionsRadiosinline\" id=\"\" value=\"\">D.选项 1\r\n" + 
	"										</label>\r\n" + 
	"									</li>\r\n" + 
	"								</ul>\r\n" + 
									"</div>"+*/
	"							</div>\r\n" + 
	"						</div>\r\n" + 
	"					</div>";
	
	
	$("#topicContainer").append(topicHtml);
}
function leavePage(){
	if($('#submit_flag').val()==0)return '您输入的内容尚未保存，确定离开此页面吗？';
}
/* 下拉选择科目加载后台信息 */
$(function() {  
    $(".selectpicker").selectpicker({  
        noneSelectedText : '请选择'  
        });  
  
        $(window).on('load', function() {  
        $('.selectpicker').selectpicker('val', '');  
        $('.selectpicker').selectpicker('refresh');  
        });  
  
        // 下拉数据加载
    $.ajax({  
        type : 'get',  
        url :"subject/findAll",  
        dataType : 'json',  
        success : function(datas) {// 返回list数据并循环获取
            var select = $("#slpk");  
            for (var i = 0; i < datas.length; i++) {  
                select.append("<option value='"+datas[i].id+"'>"  
                        + datas[i].name + "</option>");  
            }  
            $('.selectpicker').selectpicker('val', '');  
            $('.selectpicker').selectpicker('refresh'); 
        }  
    });
});


/* 试卷信息提交保存 */
$("#form1").submit(function(envent){
	$('#submit_flag').val(1);
	
	var data = {};//传给后台的Paper对象
	/*private String title;
	private String description;
	private Subject subject;
	private CombinationType combType;
	private PaperType paperType;
	private Teacher teacher;//组卷教师
	private Integer time;   //考试时长，分钟
	private List<Topics> topics = new ArrayList<Topics>();
*/	
	var title = $("textarea[name='title']").val();
	var description = $("textarea[name='description']").val();
	var time = $("input[name='time']").val();
	var subjectId = $("#slpk").find("option:selected").val();
	var paperType = $("input[name='paperType']:checked").val();
	
	data = {
			"title":title,
			"description":description,
			"subject":{"id":subjectId},
			"combType":"Manual",
			"paperType":paperType,
			"time":time
			};
	
	/*private Long id;
	private Integer _index;
	private String title;
	private List<Subtopics> subtopics = new ArrayList<Subtopics>();*/
	var topics = new Array();//试卷大题Topics类
	var topicElements = $(".topic-item");
	
	
	for(var i=0;i<topicElements.length;i++){
		
		var topic_title_elem = $(topicElements[i]).find("input[name='topic_title']");
		var topic_title = topic_title_elem.val();
		var topic_index = $(topic_title_elem).prev().text();
		topics[i] = {
				"title":topic_title,
				"_index":topic_index
				};
		
		var subtopics = new Array();
		var subtopicElements = $(topicElements[i]).find('.subtopic-item');
		for(var j=0;j<subtopicElements.length;j++){
			/*Suptopics对象
			 * private Long id;
			private Integer _index;
			private Single single;
			private Multiple multiple;
			private Judgment judgment;
			private Explanation explanation;
			private float score;*/
			var _index = $(subtopicElements[j]).find('h4').find('span').text();
			var question_id = $(subtopicElements[j]).find("input[name='subtopic_id']").val();
			var subtopic_type = $(subtopicElements[j]).find("input[name='subtopic_type']").val();
			var score = $(subtopicElements[j]).find("input[name='subtopic_score']").val();
			
			subtopics[j] = {
					"_index":_index,
					"score":score
					};
			if(subtopic_type == 'Single'){
				$(subtopics[j]).attr("single",{"id":question_id});
			}else if(subtopic_type == 'Multiple'){
				$(subtopics[j]).attr("multiple",{"id":question_id});
			}else if(subtopic_type == 'Judgment'){
				$(subtopics[j]).attr("judgment",{"id":question_id});
			}else if(subtopic_type == 'Explanation'){
				$(subtopics[j]).attr("explanation",{"id":question_id});
			}else{}
		}
		$(topics[i]).attr("subtopics",subtopics);
		
	}
	$(data).attr("topics",topics);
	
	var result = JSON.stringify(data);//string类型
	
	$.ajax({
		url:'paper/save',
		type:'post',
		dataType:'json',
		data:{paper:result},
		success:function(data){
			alert(data.msg);
			if(data.success){
				window.location.href = "tch_paper.jsp";
			}
		},
		error:function(){
			$('#submit_flag').val(0);
			alert("出错!");
		}
	});
	return false;
});